-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreversellinplace.py
More file actions
69 lines (48 loc) · 1.38 KB
/
reversellinplace.py
File metadata and controls
69 lines (48 loc) · 1.38 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""Given linked list, reverse the nodes in this linked list in place.
Iterative solution doctest:
>>> ll1 = LinkedList(Node(1, Node(2, Node(3))))
>>> ll1.as_string()
'123'
>>> reverse_linked_list_in_place(ll1)
>>> ll1.as_string()
'321'
"""
class LinkedList(object):
"""Linked list."""
def __init__(self, head=None):
self.head = head
def as_string(self):
"""Represent data for this list as a string.
>>> LinkedList(Node(3)).as_string()
'3'
>>> LinkedList(Node(3, Node(2, Node(1)))).as_string()
'321'
"""
out = []
n = self.head
while n:
out.append(str(n.data))
n = n.next
return "".join(out)
class Node(object):
"""Class in a linked list."""
def __init__(self, data, next=None):
self.data = data
self.next = next
# Iteration solution.
def reverse_linked_list_in_place(lst):
"""Given linked list, reverse the nodes in this linked list in place."""
prev = None
current = lst.head
ahead = current.next
while current.next:
current.next = prev
prev = current
current = ahead
ahead = current.next
current.next = prev
lst.head = current
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. RIGHT ON!\n"