Fastest way to find the middle node in a linked list
Anonymous
you walk the linked list with 2 pointers, one advancing on each pass, the second advancing every other pass, The second pointer will reach the middle of the list by the time the first one reaches the end. node *findmiddle(node *head) { node *walker = head; node *middle = head; boolean_t moveit = TRUE; if (head == NULL) return; // trivial case; while (walker ->next != NULL) { walker = walker->next; if (moveit) middle = middle->next; moveit = ~moveit; } return middle; }
Check out your Company Bowl for anonymous work chats.