Middle of the linked list!!


Find the middle element of the linked list just in one traversal of the list.

1- Take two pointers P1 and P2 , both pointed to the first element.

2- Increment P1 by 1 and P2 by two.

3-Whenever P2 reaches to the end, P1 will be at the middle of the list, just return P1->data.

But I think we have traversed the list for 1.5 times because P1 and P2 both traversed few nodes. Is it cheating? Could not find any better solution.

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;
}

It works fine as far as number of nodes in the list are odd. What is the middle element in case of even numbered linked list. Should we return two elements?

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: