top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

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

+2 votes
970 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 Google+ Share Button LinkedIn Share Button Multiple Social 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.
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...