-
Notifications
You must be signed in to change notification settings - Fork 0
/
206_reverse_linked_list.py
44 lines (34 loc) · 1.21 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
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: 'ListNode') -> 'ListNode':
def iterReverse(node):
if node == None:
return None
current = node
newHead = ListNode(node.val)
while current.next is not None:
newNode = ListNode(current.next.val)
newNode.next = newHead
newHead = newNode
current = current.next
return(newHead)
def recurReverse(node):
if node == None:
return(None, None)
else:
if node.next is not None:
previous, newHead = recurReverse(node.next)
current = ListNode(node.val)
previous.next = current
return(current, newHead)
else:
newHead = ListNode(node.val)
return(newHead, newHead)
#newHead = iterReverse(head)
#return(newHead)
unused, newHead = recurReverse(head)
return(newHead)