Reverse Single Linked List

How will you reverse a single linked list which consists of nodes a to z using recursion?

Questions by shyamkumar1221

Showing Answers 1 - 6 of 6 Answers

manubn

  • Nov 15th, 2010
 

Function : 


// Returns - the pointer to the starting node of the reversed linked list.
// Parameters - Previous node, Current node

Node* listReverse( Node* prev, Node* ptr )
{
   Node* res = NULL;
   if( NULL == ptr )
   {
    res = prev;
   }
   else
   {
    res = listReverse( ptr, ptr->next );
    ptr->next = prev;
   }
   return res;
}

I hope this function suffices the question.

Usage: 

Node* prev = NULL;
Node* reversedList = listReverse( prev, ptr );// ptr is the start of the linked list.

The above two answers have bugs... They don't work correctly... Here is the code


struct node* reverse(node *head)
{
   node *current=NULL;
  if(head->next==NULL)
  {
      //we have only one element in our list
      current=head;
  }
  else
 {
    current=reverse(head->next);
    head->next->next=head;
    head->next=NULL;
 }
 return current;
}

  Was this answer useful?  Yes

shri

  • Jul 15th, 2011
 

//hope this may work

Code
  1. span style="font-style: italic;">//we have only one element in our list

  Was this answer useful?  Yes

sasibhushan.m

  • Jul 30th, 2011
 

node* reverse_recursive(node *root)
{
if(root->link != NULL)
{
reverse_recursive(root->link);
root->link->link = root;
return (root);
}
else
{
head = root;
}
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions