forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse-linked-list.py
45 lines (37 loc) · 1.03 KB
/
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
# Time: O(n)
# Space: O(1)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
# Iterative solution.
class Solution(object):
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
dummy = ListNode(float("-inf"))
while head:
dummy.next, head.next, head = head, dummy.next, head.next
return dummy.next
# Time: O(n)
# Space: O(n)
# Recursive solution.
class Solution2(object):
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
[begin, end] = self.reverseListRecu(head)
return begin
def reverseListRecu(self, head):
if not head:
return [None, None]
[begin, end] = self.reverseListRecu(head.next)
if end:
end.next = head
head.next = None
return [begin, head]
else:
return [head, head]