top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to find mid point of singly linked list in a single pass only ?

+2 votes
1,376 views
How to find mid point of singly linked list in a single pass only ?
posted Oct 23, 2013 by Priyanshi Goyal

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
traverse once with two pointers
  use one pointer which is moving once at one go.
  other pointer which will move twice in one go.
  at the end 1st pointer will be the middle element.

1 Answer

+2 votes
 
Best answer

Is this considered as single pass, traversing the list once but using two variables.

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;    
}
answer Oct 23, 2013 by Salil Agrawal
Yes Salil. As I understand this will be good solution to find middle. And for this code the list should contain minimum one node otherwise it leads to segmentation error as we do not have NULL check for head/first node.

But what is the use of integer "mid" here ..   why you are returning data of middle node.
good catch,
1. we need to add a check p==null then return.
2. mid is unused variable, compiler warning.
3. One can return the middle node or data on the middle node depends on the case.
...