Skip to content

Commit 4561148

Browse files
committed
feat: 143. Reorder List : 反转链表 + 双指针
1 parent c96d472 commit 4561148

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @return {void} Do not return anything, modify head in-place instead.
11+
*/
12+
const reorderList = function (head) {
13+
let sz = 0; let a = head
14+
while (a) sz++, a = a.next
15+
16+
a = head
17+
for (let i = 0; i < Math.floor((sz - 1) / 2); i++) {
18+
a = a.next
19+
}
20+
let head2 = a.next
21+
a.next = null
22+
head2 = reverse(head2)
23+
24+
const dummy = new ListNode()
25+
let p = head; let q = head2; let cur = dummy
26+
while (p || q) {
27+
if (p) {
28+
cur.next = p
29+
p = p.next
30+
cur = cur.next
31+
}
32+
if (q) {
33+
cur.next = q
34+
q = q.next
35+
cur = cur.next
36+
}
37+
}
38+
return dummy.next
39+
}
40+
41+
function reverse (head) {
42+
if (!head) return null
43+
let a = head; let b = a.next
44+
head.next = null
45+
while (b) {
46+
const c = b.next
47+
b.next = a
48+
a = b, b = c
49+
}
50+
return a
51+
}

leetcode/残酷刷题/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@
173173
- 92. Reverse Linked List II
174174
- 25. Reverse Nodes in k-Group
175175
- 2074. Reverse Nodes in Even Length Groups
176+
- 143. Reorder List
176177

177178
## Links
178179

0 commit comments

Comments
 (0)