Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 622c10e

Browse files
author
zhangxing
committed
feat: 链表
1 parent fdccb77 commit 622c10e

File tree

4 files changed

+73
-1
lines changed

4 files changed

+73
-1
lines changed

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.history/
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// 1->2->3->4->5
2+
// 2->1->4->3->5
3+
4+
const { ListNode, makeList } = require('./创建单链表');
5+
let list = makeList([1, 2, 3, 4]);
6+
7+
var swapPairs = function (head) {
8+
if (!head) return head;
9+
10+
let k = 0,
11+
pre = head,
12+
cur = pre.next,
13+
lastEnd = null; // 上一个分组交换后的第二个元素
14+
15+
while (cur) {
16+
let temp = cur.next,
17+
front = pre,
18+
end = cur;
19+
20+
end.next = front;
21+
front.next = temp;
22+
if (lastEnd) {
23+
lastEnd.next = end; // 指向当前循环内的分组交换后的第一个元素
24+
}
25+
if (k === 0) {
26+
list.head = end;
27+
}
28+
29+
if (!temp) {
30+
break;
31+
}
32+
pre = temp;
33+
cur = temp.next;
34+
lastEnd = front;
35+
k++;
36+
}
37+
return list.head;
38+
};
39+
40+
swapPairs(list.head);
41+
list.print();

‎链表/61.旋转链表.js‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// 1->2->3->4->5
2+
// k = 1: 5->1->2->3->4
3+
// k = 2: 4->5->1->2->3
4+
const { ListNode, makeList } = require('./创建单链表');
5+
let list = makeList([1]);
6+
7+
var rotate = function (head, k) {
8+
if (!head || !head.next) return head;
9+
10+
while (k--) {
11+
// 找到尾结点和尾结点的前驱结点
12+
let pre = head,
13+
cur = pre.next;
14+
while (cur.next) {
15+
pre = cur;
16+
cur = cur.next;
17+
}
18+
// cur就是尾结点,pre是尾结点的前驱结点
19+
// 旋转
20+
cur.next = head;
21+
pre.next = null;
22+
head = cur;
23+
24+
list.head = cur;
25+
list.print();
26+
}
27+
};
28+
29+
rotate(list.head, 10);
30+
// list.print();

‎链表/反转链表92.js‎ renamed to ‎链表/92.反转链表.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,4 @@ var reverseBetween = function (head, left, right) {
6262
};
6363

6464
reverseBetween(list.head, 2, 4);
65-
console.log(list.print());
65+
list.print();

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /