链表重排序。题意很简单,

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

You may not modify the values in the list's nodes, only nodes itself may be changed.

例子

思路也很直观,但是代码容易错,算是链表题里面的综合题吧,有链表的快慢指针,反转,和merge两个链表三个技能点的考察。

时间O(n)

空间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 };
12-29 10:47