-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path206.py
63 lines (54 loc) · 1.45 KB
/
206.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
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def create_linked_list(arr):
head = ListNode(arr[0])
cur = head
for i in range(1, len(arr)):
cur.next = ListNode(arr[i])
cur = cur.next
return head
def print_linked_list(head):
cur = head
res = []
while cur:
res.append(cur.val)
cur = cur.next
return res
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
p = head
p_last = p
p = p.next
p_next = p.next
# head.next = None
while p is not None:
p.next = p_last
p_last = p
p = p_next
if p is None:
break
p_next = p.next
head.next = None
return p_last
def reverseList2(self, head):
def reverseList2_inner(head):
if head is None or head.next is None:
return head
last = reverseList2_inner(head.next)
head.next.next = head
head.next = None
return last
return reverseList2_inner(head)
if __name__ == '__main__':
soul = Solution()
l1 = create_linked_list([1,2,3,4,5])
print(print_linked_list(soul.reverseList2(l1)))