Skip to content

Commit 38210e1

Browse files
committed
completed reverse.py with a runtime complexity of O(n)
1 parent 9eec445 commit 38210e1

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

reverse/reverse.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,26 @@ def contains(self, value):
4747

4848
def reverse_list(self, node, prev):
4949
# You must use recursion for this solution
50-
pass
50+
51+
# Case where list is empty; do nothing
52+
if not self.head:
53+
pass
54+
# Base case
55+
elif not node.get_next():
56+
# This means the node is the original tail,
57+
# so make it the new head.
58+
# (This also applies if the list has one element,
59+
# since then the head just is the tail.)
60+
self.head = node
61+
# In all cases, the "prev" argument contains the node's
62+
# old previous node. Since we're reversing, we want this
63+
# to be its next node.
64+
node.set_next(prev)
65+
else:
66+
# Save the node's current next node; we'll be passing
67+
# it through the function soon.
68+
old_next = node.get_next()
69+
node.set_next(prev)
70+
# Re-run the function on "old_next", with the "prev" argument
71+
# being "node" for reasons outlined above.
72+
self.reverse_list(old_next, node)

0 commit comments

Comments
 (0)