-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.ts
37 lines (35 loc) · 868 Bytes
/
Solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function reverseBetween(head: ListNode | null, left: number, right: number): ListNode | null {
const n = right - left;
if (n === 0) {
return head;
}
const dummy = new ListNode(0, head);
let pre = null;
let cur = dummy;
for (let i = 0; i < left; i++) {
pre = cur;
cur = cur.next;
}
const h = pre;
pre = null;
for (let i = 0; i <= n; i++) {
const next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
h.next.next = cur;
h.next = pre;
return dummy.next;
}