Reverse a linked list

PROBLEM :

You’re given the pointer to the head node of a linked list. Change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty.

Input Format
You have to complete the Node* Reverse(Node* head) method which takes one argument - the head of the linked list. You should NOT read any input from stdin/console.

Output Format
Change the next pointers of the nodes that their order is reversed and return the head of the reversed linked list. Do NOT print anything to stdout/console.

Sample Input

NULL
2 --> 3 --> NULL

Sample Output

NULL
3 --> 2 --> NULL

Explanation
1. Empty list remains empty
2. List is reversed from 2,3 to 3,2

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*
  Reverse a linked list and return pointer to the head
  The input list will have at least one element
  Node is defined as
  struct Node
  {
     int data;
     struct Node *next;
  }
*/
struct Node* Reverse(struct Node *head)
{
    if(head==NULL)
        return NULL ;
 
    if(head->next==NULL)
            return head ;
 
  struct Node *p1,*p2,*p3 ;
    p1=head ;
    p2=p1->next ;
    p3=p2->next ;
 
    p2->next=p1 ;
    p1->next=NULL ;
 
    while(p3!=NULL)
        {
        p1=p2 ;
        p2=p3 ;
        p3=p3->next ;
     
        p2->next=p1 ;
    }
    head=p2 ;
    return head ;
}


---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )