File tree Expand file tree Collapse file tree 1 file changed +92
-0
lines changed Expand file tree Collapse file tree 1 file changed +92
-0
lines changed Original file line number Diff line number Diff line change 1+ # 143. Reorder List
2+
3+ - Difficulty: Medium.
4+ - Related Topics: Linked List.
5+ - Similar Questions: .
6+
7+ ## Problem
8+
9+ Given a singly linked list ** L** : ** L** 0→** L** 1→…→** L**** n** -1→** L** n,
10+ reorder it to: ** L** 0→** L**** n** →** L** 1→** L**** n** -1→** L** 2→** L**** n** -2→…
11+
12+ You may ** not** modify the values in the list's nodes, only nodes itself may be changed.
13+
14+ ** Example 1:**
15+
16+ ```
17+ Given 1->2->3->4, reorder it to 1->4->2->3.
18+ ```
19+
20+ ** Example 2:**
21+
22+ ```
23+ Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
24+ ```
25+
26+ ## Solution
27+
28+ ``` javascript
29+ /**
30+ * Definition for singly-linked list.
31+ * function ListNode(val) {
32+ * this.val = val;
33+ * this.next = null;
34+ * }
35+ */
36+ /**
37+ * @param {ListNode} head
38+ * @return {void} Do not return anything, modify head in-place instead.
39+ */
40+ var reorderList = function (head ) {
41+ if (! head || ! head .next || ! head .next .next ) return ;
42+
43+ // find mid
44+ var mid = null ;
45+ var fast = head;
46+ var slow = head;
47+ while (fast .next && fast .next .next && slow .next ) {
48+ slow = slow .next ;
49+ fast = fast .next .next ;
50+ }
51+ mid = slow;
52+
53+ // reverse the later part
54+ var now = mid .next .next ;
55+ var second = mid .next ;
56+ var tmp = null ;
57+ second .next = null ;
58+ while (now) {
59+ tmp = now .next ;
60+ now .next = second;
61+ second = now;
62+ now = tmp;
63+ }
64+ mid .next = second;
65+
66+ // insert one after another
67+ var before = head;
68+ var after = mid .next ;
69+ mid .next = null ;
70+ while (after) {
71+ tmp = before .next ;
72+ before .next = after;
73+ before = tmp;
74+ tmp = after .next ;
75+ after .next = before;
76+ after = tmp
77+ }
78+ };
79+ ```
80+
81+ ** Explain:**
82+
83+ 比如 ` 1->2->3->4->5->6 ` ,分三步
84+
85+ 1 . 找到 ` mid = 3 `
86+ 2 . 翻转后半部分,变成 ` 1->2->3->6->5->4 `
87+ 3 . 后半部分依次插入到前半部分
88+
89+ ** Complexity:**
90+
91+ * Time complexity : O(n).
92+ * Space complexity : O(1).
You can’t perform that action at this time.
0 commit comments