Wednesday, 9 December 2015

Reverse linked list - iterative

Reverse linked list





/*
  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;
  }
*/
Node* Reverse(Node *head)
{
    if(head == NULL)
        return head;
    Node *z = NULL;
    Node *x = head;
    Node *y = x -> next;
    x -> next =  NULL;
    while(y != NULL)
        {
        z = y -> next;
        y -> next = x;
        x = y;
        y = z;
    }
    head = x;
    return head;
}

No comments:

Post a Comment