-
Notifications
You must be signed in to change notification settings - Fork 441
/
Copy pathreverse_linked_list.py
68 lines (41 loc) · 1.14 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Node(object):
""" Class in a linked list. """
def __init__(self, data, next=None):
self.data = data
self.next = next
def as_string(self):
"""Represent data for this node and it's successors as a string.
>>> Node(3).as_string()
'3'
>>> Node(3, Node(2, Node(1))).as_string()
'321'
"""
out = []
n = self
while n:
out.append(str(n.data))
n = n.next
return ''.join(out)
def reverse_linked_list(head):
"""Given singly linked list head node, return head node of new, reversed linked list.
>>> ll = Node(1, Node(2, Node(3)))
>>> reverse_linked_list(ll).as_string()
'321'
>>> ll = Node(1, Node(2, Node(3)))
>>> new_ll = reverse_linked_list(ll)
>>> new_ll.as_string()
'321'
"""
prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
if __name__ == '__main__':
import doctest
results = doctest.testmod()
if results.failed == 0:
print "ALL TESTS PASSED!"