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)
struct node *p1,*p2;
while(p2->link != NULL && p2->link->link != NULL)
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?