i tried following function to find middle element of singly linked list, but its not working. Can anyone help please?
Code:
findmiddle(node *head){
node *p1, *p2;
p1 = head;
p2 = head;
while(p1!=NULL) {
p1 = p1->next->next;
p2 = p2->next;
}
printf("Middle = %d", p2->data);
}
i am using this algorithm
Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer reaches end slow pointer will reach middle of the linked list.
UPDATE:
i added 1 condition in while loop and now its working
while(p1!=NULL && p1->next!= NULL)