Skip to content

Commit 477b2c2

Browse files
Hacktoberfest: Update Linked List - print_reverse method (TheAlgorithms#2792)
* chore: update print_reverse helper method Use a generator expression instead of slicing `elements_list` to improve the space and time complexity of `make_linked_list` to O(1) space and O(n) time by avoiding the creation a shallow copy of `elements_list`. * fix: add type checking and argument typing Add argument typing to all methods in `print_reverse` Add doctest to helper function `make_linked_list` and basic edge case tests to `print_reverse` * test: add `print_reverse` test Fix doctest syntax and remove edge case tests that are covered by typed arguments. Add `print_reverse` test that expects the correct values are printed out by adding a `test_print_reverse_output` helper function. * format code Co-authored-by: shellhub <[email protected]>
1 parent 437c725 commit 477b2c2

File tree

1 file changed

+44
-29
lines changed

1 file changed

+44
-29
lines changed

Diff for: data_structures/linked_list/print_reverse.py

+44-29
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Program to print the elements of a linked list in reverse
1+
from typing import List
22

33

44
class Node:
@@ -8,48 +8,63 @@ def __init__(self, data=None):
88

99
def __repr__(self):
1010
"""Returns a visual representation of the node and all its following nodes."""
11-
string_rep = ""
11+
string_rep = []
1212
temp = self
1313
while temp:
14-
string_rep += f"<{temp.data}> ---> "
14+
string_rep.append(f"{temp.data}")
1515
temp = temp.next
16-
string_rep += "<END>"
17-
return string_rep
16+
return "->".join(string_rep)
1817

1918

20-
def make_linked_list(elements_list):
19+
def make_linked_list(elements_list: List):
2120
"""Creates a Linked List from the elements of the given sequence
22-
(list/tuple) and returns the head of the Linked List."""
23-
24-
# if elements_list is empty
21+
(list/tuple) and returns the head of the Linked List.
22+
>>> make_linked_list([])
23+
Traceback (most recent call last):
24+
...
25+
Exception: The Elements List is empty
26+
>>> make_linked_list([7])
27+
7
28+
>>> make_linked_list(['abc'])
29+
abc
30+
>>> make_linked_list([7, 25])
31+
7->25
32+
"""
2533
if not elements_list:
2634
raise Exception("The Elements List is empty")
2735

28-
# Set first element as Head
29-
head = Node(elements_list[0])
30-
current = head
31-
# Loop through elements from position 1
32-
for data in elements_list[1:]:
33-
current.next = Node(data)
36+
current = head = Node(elements_list[0])
37+
for i in range(1, len(elements_list)):
38+
current.next = Node(elements_list[i])
3439
current = current.next
3540
return head
3641

3742

38-
def print_reverse(head_node):
39-
"""Prints the elements of the given Linked List in reverse order"""
40-
41-
# If reached end of the List
42-
if head_node is None:
43-
return None
44-
else:
45-
# Recurse
43+
def print_reverse(head_node: Node) -> None:
44+
"""Prints the elements of the given Linked List in reverse order
45+
>>> print_reverse([])
46+
>>> linked_list = make_linked_list([69, 88, 73])
47+
>>> print_reverse(linked_list)
48+
73
49+
88
50+
69
51+
"""
52+
if head_node is not None and isinstance(head_node, Node):
4653
print_reverse(head_node.next)
4754
print(head_node.data)
4855

4956

50-
list_data = [14, 52, 14, 12, 43]
51-
linked_list = make_linked_list(list_data)
52-
print("Linked List:")
53-
print(linked_list)
54-
print("Elements in Reverse:")
55-
print_reverse(linked_list)
57+
def main():
58+
from doctest import testmod
59+
60+
testmod()
61+
62+
linked_list = make_linked_list([14, 52, 14, 12, 43])
63+
print("Linked List:")
64+
print(linked_list)
65+
print("Elements in Reverse:")
66+
print_reverse(linked_list)
67+
68+
69+
if __name__ == "__main__":
70+
main()

0 commit comments

Comments
 (0)