Skip to content

Commit 34244e6

Browse files
committed
feat(每日一题): ✨考察链表基本操作
1 parent 75bc7e7 commit 34244e6

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
const reorderList = head => {
2+
if (!head || !head.next) {
3+
return head;
4+
}
5+
6+
const half = findHalf(head);
7+
const secondHalf = half.next;
8+
half.next = null;
9+
10+
let newSecondHalf = reverseLinkedList(secondHalf);
11+
12+
// 合并
13+
let currentHead = head;
14+
while (currentHead && newSecondHalf) {
15+
const x = currentHead.next;
16+
const y = newSecondHalf.next;
17+
currentHead.next = newSecondHalf;
18+
newSecondHalf.next = x;
19+
currentHead = x;
20+
newSecondHalf = y;
21+
}
22+
}
23+
24+
// 寻找链表中间值
25+
function findHalf(head) {
26+
let fast = head;
27+
let slow = head;
28+
while (fast && fast.next) {
29+
fast = fast.next.next;
30+
slow = slow.next;
31+
}
32+
33+
return slow;
34+
}
35+
36+
// 翻转链表
37+
function reverseLinkedList(head) {
38+
if (!head || !head.next) {
39+
return head;
40+
}
41+
42+
let nextNode = head.next;
43+
head.next = null;
44+
while (nextNode) {
45+
const temp = nextNode.next;
46+
nextNode.next = head;
47+
head = nextNode;
48+
nextNode = temp;
49+
}
50+
51+
return head;
52+
}

0 commit comments

Comments
 (0)