Skip to content

Commit 7782fd6

Browse files
committed
feat: reverse-linkedlist from m to n
1 parent 76ffe7d commit 7782fd6

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

public/code/linkedlist.tsx

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ let sections = [
7272
// 206. 反转链表
7373
() => {
7474
function reverseLinkedList<T>(head: ListNode<T>): ListNode<T> {
75-
head = _.cloneDeep(head)
75+
head = _.cloneDeep(head) // avoid mutating original
7676
let prev = null
7777
let curr = head
7878
while (curr) {
@@ -94,6 +94,44 @@ let sections = [
9494
)
9595
},
9696

97+
// 92. 反转链表 II
98+
() => {
99+
function reverseLinkedList<T>(head: ListNode<T>, m: number, n: number): ListNode<T> {
100+
head = _.cloneDeep(head)
101+
let start = head
102+
let curr = head
103+
let beforeStart = null
104+
let id = 1
105+
while (id < m) {
106+
let next = curr.next
107+
beforeStart = curr
108+
curr = next
109+
id++
110+
}
111+
let afterEnd = curr
112+
let prev = null
113+
while (id <= n) {
114+
let next = curr.next
115+
curr.next = prev
116+
prev = curr
117+
curr = next
118+
id++
119+
}
120+
beforeStart.next = prev
121+
afterEnd.next = curr
122+
return start
123+
}
124+
let before = createLinkedList([1, 2, 3, 4, 5, 6, 7])
125+
let after = reverseLinkedList(before, 3, 6)
126+
return (
127+
<section>
128+
<h4>92. 反转链表 II</h4>
129+
<div>{stringifyLinkedList(before)}</div>
130+
<div>Reverse: {stringifyLinkedList(after)}</div>
131+
</section>
132+
)
133+
},
134+
97135
// 876. 链表的中间节点 - 双指针-快慢指针
98136
() => {
99137
function getMiddleListNode<T>(head: ListNode<T>): ListNode<T> {

public/code/linkedlist.tsx.png

45.2 KB
Loading

0 commit comments

Comments
 (0)