Pergunta de entrevista da empresa Salesforce

Fastest way to find the middle node in a linked list

Respostas da entrevista

Sigiloso

30 de nov. de 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

Sigiloso

20 de mar. de 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

Sigiloso

10 de jul. de 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

Sigiloso

26 de set. de 2012

how's that the middle node?

1

Sigiloso

22 de set. de 2014

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