Sunday, January 29, 2012

Get middle node of a linked list


Write a C function to print the middle of a given linked list


Method:Two Pointers
Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer reaches end slow pointer will reach middle of the linked list.

struct node* GetMiddle(struct node *head)
{
  struct node *slow_ptr = head;
  struct node *fast_ptr = head;
 
  if(head!=NULL)
  {
       while((fast_ptr->link)!=NULL &&
               (fast_ptr->link->link)!=NULL)
       {
          fast_ptr = fast_ptr->link->link;
          slow_ptr = slow_ptr->link;
       }
       return slow_ptr;
  }
}

1 comment: