-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path092 Reverse Linked List II.py
60 lines (51 loc) · 1.34 KB
/
092 Reverse Linked List II.py
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
54
55
56
57
58
59
60
'''
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def to_list(self):
return [self.val] + self.next.to_list() if self.next else [self.val]
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
dummy = ListNode(-1)
dummy.next = head
node = dummy
for __ in range(m - 1):
node = node.next
prev = node.next
curr = prev.next
for __ in range(n - m):
next = curr.next
curr.next = prev
prev = curr
curr = next
node.next.next = curr
node.next = prev
return dummy.next
if __name__ == "__main__":
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n5 = ListNode(5)
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
r = Solution().reverseBetween(n1, 2, 4)
assert r.to_list() == [1, 4, 3, 2, 5]