Tuesday, August 21, 2012

How to find middle of a linked list in single pass.

To find the middle element of a linklist in single pass.

  1.  Take two pointers P1 and P2, both pointed to the first element.
  2.  Increment P1 by 1 and P2 by 2.
  3.  Whenever P2 reaches to the end, P1 will be at the middle of the list"

int getMiddle(struct node *p)
{
  int mid;
  struct node *p1,*p2;
  p1=p2=p;
  while(p2->link != NULL && p2->link->link != NULL)
  {
    p1=p1->link;
    p2=p2->link->link;
  }
  return p1->data;
}

No comments:

Post a Comment