forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse-linked-list.py
More file actions
45 lines (40 loc) · 1.13 KB
/
reverse-linked-list.py
File metadata and controls
45 lines (40 loc) · 1.13 KB
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
#https://leetcode.com/problems/reverse-linked-list/
# class Solution(object):
# #iterative
# def reverseList(self, head):
# prev = None
# current = head
# while current:
# temp = current.next
# current.next = prev
# prev = current
# current = temp
# return prev
# #recursive
# def reverseList(self, head):
# if head is None or head.next is None:
# return head
# new_head = self.reverseList(head.next)
# n = head.next
# n.next = head
# head.next = None
# return new_head
#recursive
class Solution(object):
def reverseList(self, node):
if node and node.next:
new_head = self.reverseList(node.next)
node.next.next = node
node.next = None
return new_head
return node
#iterative
class Solution(object):
def reverseList(self, node):
pre = None
while node:
next_node = node.next
node.next = pre
if not next_node: return node
pre = node
node = next_node