-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0092-reverse-linked-list-ii.py
More file actions
53 lines (42 loc) · 1.12 KB
/
0092-reverse-linked-list-ii.py
File metadata and controls
53 lines (42 loc) · 1.12 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# time complexity: O(n)
# space complexity: O(1)
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
if not head:
return
node = head
prev = None
for _ in range(left - 1):
prev = node
node = node.next
right -= 1
tail, con = node, prev
for _ in range(right):
nextNode = node.next
node.next = prev
prev = node
node = nextNode
if con:
con.next = prev
else:
head = prev
tail.next = node
return head
def traverse(node: Optional[ListNode]):
if node is None:
return
print(node.val)
traverse(node.next)
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
left = 2
right = 4
traverse(Solution().reverseBetween(head, left, right))