-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse.py
100 lines (63 loc) · 1.84 KB
/
reverse.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/env python3
class LinkedList:
def __init__ (self, x) :
self.value = x
self.next = None
def get_value (self) :
return self.value
def set_value (self, x) :
self.value = x
def get_next (self) :
return self.next
def set_next (self, node) :
self.next = node
def reverse (l) :
def reverse_aux (n1, n2) :
if n2 == None :
return n1
else :
n3 = n2.get_next ()
n2.set_next (n1)
return reverse_aux (n2, n3)
return reverse_aux (None, l)
def iterate (f, l) :
if l == None :
return
else :
f (l.get_value ())
return iterate (f, l.get_next ())
def print_list (l) :
iterate ((lambda s : print (str (s) + " ", end = '')), l)
print ()
def main () :
l1 = LinkedList (1)
l2 = LinkedList (2)
l3 = LinkedList (3)
l4 = LinkedList (4)
l5 = LinkedList (5)
lists = [ ("l1", l1) , ("l2", l2)
, ("l3", l3) , ("l4", l4)
, ("l5", l5)
]
print ()
print (">>> Before linking the lists")
list (map (lambda p : print (p [0] + " : ", end = '') or print_list (p [1]), lists))
l1.set_next (l2)
l2.set_next (l3)
l3.set_next (l4)
l4.set_next (l5)
print ()
print (">>> After linking and before reversing the linked list")
list (map (lambda p : print (p [0] + " : ", end = '') or print_list (p [1]), lists))
print ()
print ("\
The execution of `reverse l1´ computes the reversed\n\
list of l1 and the returned result is equal to l5,\n\
the new head of the linked list.\n\
")
reverse (l1)
print (">>> After reversing the linked list")
list (map (lambda p : print (p [0] + " : ", end = '') or print_list (p [1]), lists))
print ()
if __name__ == "__main__" :
main ()