Salesforce Interview Question

Fastest way to find the middle node in a linked list

Interview Answers

Anonymous

Nov 30, 2012

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

10

Anonymous

Jul 10, 2012

node* FindMiddle(node* head) { if (!head) return null; // error node* fast = head; // fast pointer while (fast->next && fast->next->next) // fast->next->next will not be evaluated in fast->next == null { head = head->next; fast = fast->next->next; } return head; }

6

Anonymous

Mar 20, 2016

ListNode findMiddle(ListNode head) { if(head == null || head.next == null) return head; ListNode slow = head, fast = head; while(fast != null, fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; }

3

Anonymous

Sep 26, 2012

how's that the middle node?

1

Anonymous

Sep 22, 2014

Why wouldn't you just check the head, and then do list.get(list.size()/2)?