File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ class Node (object ):
2+ """ Class in a linked list. """
3+
4+ def __init__ (self , data , next = None ):
5+ self .data = data
6+ self .next = next
7+
8+ def as_string (self ):
9+ """Represent data for this node and it's successors as a string.
10+
11+ >>> Node(3).as_string()
12+ '3'
13+
14+ >>> Node(3, Node(2, Node(1))).as_string()
15+ '321'
16+ """
17+
18+ out = []
19+ n = self
20+
21+ while n :
22+ out .append (str (n .data ))
23+ n = n .next
24+
25+ return '' .join (out )
26+
27+
28+ def reverse_linked_list (head ):
29+ """Given singly linked list head node, return head node of new, reversed linked list.
30+
31+ >>> ll = Node(1, Node(2, Node(3)))
32+ >>> reverse_linked_list(ll).as_string()
33+ '321'
34+
35+ >>> ll = Node(1, Node(2, Node(3)))
36+ >>> new_ll = reverse_linked_list(ll)
37+ >>> new_ll.as_string()
38+ '321'
39+ """
40+
41+ prev = None
42+ curr = head
43+
44+ while curr :
45+ next = curr .next
46+ curr .next = prev
47+ prev = curr
48+ curr = next
49+
50+
51+ return prev
52+
53+
54+
55+
56+
57+
58+
59+
60+
61+
62+
63+ if __name__ == '__main__' :
64+ import doctest
65+ results = doctest .testmod ()
66+
67+ if results .failed == 0 :
68+ print "ALL TESTS PASSED!"
You can’t perform that action at this time.
0 commit comments