-
Notifications
You must be signed in to change notification settings - Fork 1
/
ReverseLinkedListII.py
65 lines (52 loc) · 1.41 KB
/
ReverseLinkedListII.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
61
62
63
64
65
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if m == n:
return head
original = head
count = 1
last = None
while count < m:
last = head
head = head.next
count += 1
if m == 1:
end = head
else:
end = last
last = head
head = head.next
count += 1
while count <= n:
temp = head.next
head.next = last
last = head
head = temp
count += 1
if m == 1:
end.next = head
print "LIST:"
og_end = last
while last.next != None:
print last.val
last = last.next
return og_end
else:
end.next.next = head
end.next = last
print "LIST:"
end = original
while end != None:
print end.val
end = end.next
return original