Saturday, September 24, 2011

Reverse a Linked List - Iterative Solution

Function to reverse a linked list - iterative solution


void reverse(struct node *first)
{
  // p is used to traverse the linked list
  struct node *p = first;
  // q points to the start of the reversed list
  struct node *q = NULL;
  // r is a temporary variable used in this process
  struct node *r;

  while(p)
  {
    r = q;
    q = p;
    p = p -> link;
    q -> link = r;
  }
  first = q;
}

Written by

No comments:

Post a Comment