-
Notifications
You must be signed in to change notification settings - Fork 0
/
206_reverse_linked_list.py
74 lines (58 loc) · 1.24 KB
/
206_reverse_linked_list.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
66
67
68
69
70
71
72
73
74
'''
206. Reverse Linked List
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Methods:
1. iterative
2. recursive
'''
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# iterative - use extra linked list
def reverse(head):
if head is None:
return
cur = head
p = ListNode(head.val, None)
cur = cur.next
while cur:
p = ListNode(cur.val, p)
cur = cur.next
return p
# iterative - in place
def reverse2(head):
if head is None:
return None
if head.next is None:
return head
cur = head
pre = None
next = cur
while cur:
next = next.next
cur.next = pre
pre = cur
cur = next
return pre
# recursive
def reverse_rec(head):
if head is None or head.next is None:
return head
nh = reverse_rec(head.next)
head.next.next = head
head.next = None
return nh
a = ListNode(5, None)
b = ListNode(4, a)
c = ListNode(3, b)
d = ListNode(2,c)
head = ListNode(1,d)
# head = ListNode(1,None)
ls = reverse_rec(head)
print(ls)