Reordering the list. Meaning of the questions is very simple,
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
example
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
The idea is straightforward, but the code is easy wrong, be regarded as a comprehensive list of questions inside the title bar, there is a linked list pointer speed, reverse, and inspect merge two lists three skill points.
Time O (n)
Space O (1)
1 /** 2 * @param {ListNode} head 3 * @return {void} Do not return anything, modify head in-place instead. 4 */ 5 var reorderList = function(head) { 6 if (!head || !head.next) return; 7 let fast = head; 8 let slow = head; 9 while (fast && fast.next) { 10 fast = fast.next.next; 11 slow = slow.next; 12 } 13 let second = reverseList(slow.next); 14 slow.next = null; 15 let first = head; 16 while (second) { 17 let temp = second.next; 18 second.next = first.next; 19 first.next = second; 20 first = first.next.next; 21 second = temp; 22 } 23 }; 24 25 var reverseList = function(head) { 26 let pre = null; 27 while (head !== null) { 28 let next = head.next; 29 head.next = pre; 30 pre = head; 31 head = next; 32 } 33 return pre; 34 };