Skip to content

Commit 8d3e6b8

Browse files
authored
Update 92-reverse-linked-list-ii.js
1 parent 79c1934 commit 8d3e6b8

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

92-reverse-linked-list-ii.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,3 +83,45 @@ const reverseBetween = function(head, m, n) {
8383
}
8484
return dummy.next;
8585
};
86+
87+
88+
// another
89+
90+
/**
91+
* @param {ListNode} head
92+
* @param {number} left
93+
* @param {number} right
94+
* @return {ListNode}
95+
*/
96+
const reverseBetween = function(head, left, right) {
97+
if(head == null) return head
98+
if(left === right) return head
99+
let cur = head, prev = null
100+
let step = 1
101+
while(step !== left) {
102+
prev = cur
103+
cur = cur.next
104+
step++
105+
}
106+
let l = cur
107+
while(step !== right) {
108+
cur = cur.next
109+
step++
110+
}
111+
let r = cur, next = cur.next
112+
// reverse
113+
114+
let start = l, p = null
115+
while(start !== r) {
116+
let n = start.next
117+
start.next = p
118+
p = start
119+
start = n
120+
}
121+
122+
r.next = p
123+
l.next = next
124+
if(prev) prev.next = r
125+
126+
return prev ? head : r
127+
};

0 commit comments

Comments
 (0)