Thursday, July 17, 2008

Find the middle point in a linked list by traversing only once

Node findMiddlePoint(Node list)
Node m = list;
while(list != NULL && list->next != NULL) {
m = m->next;
list = list->next->next;
return m;

If the list contains odd elements, it returns middle point. If the list contains even elements it returns the first element in the second half of the list. i.e., if the elements are (1, 2, 3, 4), it returns 3.

No comments:

Post a Comment