Skip to content

Commit

Permalink
re-solve "92. Reverse Linked List II"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Nov 1, 2024
1 parent e0947f1 commit 9e16688
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions src/reverse_linked_list_ii.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,35 @@

class Solution:
def reverseBetween(
self, head: ListNode | None, left: int, right: int
self,
head: ListNode | None,
left: int,
right: int,
) -> ListNode | None:
dummy = ListNode(-1, next=head)
last = dummy
dummy = prev = ListNode(-1, next=head)

# skip left
for _ in range(left - 1):
assert last and last.next
last = last.next
assert prev and prev.next
prev = prev.next

start = last.next
prev = start
assert prev
assert prev.next
start = prev
prev = prev.next
current = prev.next

# revert till right
for _ in range(right - left):
assert current
tmp = current.next
current.next = prev
prev = current
current = tmp

last.next = prev
assert start
start.next = current
end = current
tmp = start.next
start.next = prev
assert tmp
tmp.next = end

return dummy.next

0 comments on commit 9e16688

Please sign in to comment.