-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathreverse_linked_list.py
More file actions
executable file
·44 lines (33 loc) · 1.09 KB
/
reverse_linked_list.py
File metadata and controls
executable file
·44 lines (33 loc) · 1.09 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
#!/usr/bin/python
# vim: foldlevel=0
"""
Write a program to reverse the direction of a given singly-linked list.
In other words, after the reversal all pointers should now point backwards.
Your algorithm should take linear time.
http://nbl.cewit.stonybrook.edu/algowiki/index.php/Data-structures-TADM2E-2
"""
from linked_list import randlinkedlist
ll = randlinkedlist()
print "The linked list: {0}".format(ll)
def reverse_iterative(linked_list):
prev, node = None, linked_list.head
while node:
nnext = node.next
node.next = prev
if nnext is None:
linked_list.head = node
prev, node = node, nnext
linked_list.head = prev
def _reverse(node, prev):
if node is None:
return prev
nnext = node.next
node.next = prev
return _reverse(nnext, node)
def reverse_recursive(linked_list):
new_head = _reverse(linked_list.head, None)
linked_list.head = new_head
reverse_iterative(ll)
print "The reversed linked list (iterative): {0}".format(ll)
reverse_recursive(ll)
print "The reversed linked list (recursive): {0}".format(ll)