-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.py
More file actions
37 lines (29 loc) · 886 Bytes
/
Copy pathSolution.py
File metadata and controls
37 lines (29 loc) · 886 Bytes
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
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
if head is None or head.next is None or n == m:
return head
preHead = None
result = head
changeLen = n - m + 1
while head is not None and m - 1 > 0:
preHead = head
head = head.next
m = m - 1
modifyListTail = head
newHead = None
while head is not None and changeLen > 0:
next = head.next
head.next = newHead
newHead = head
changeLen = changeLen - 1
head = next
modifyListTail.next = head
if preHead is not None:
preHead.next = newHead
else:
result = newHead
return result