2020-10-05 11:08:57 +00:00
|
|
|
from typing import List
|
2019-11-10 08:47:04 +00:00
|
|
|
|
2019-11-14 18:59:43 +00:00
|
|
|
|
2019-11-10 08:47:04 +00:00
|
|
|
class Node:
|
|
|
|
def __init__(self, data=None):
|
|
|
|
self.data = data
|
|
|
|
self.next = None
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
"""Returns a visual representation of the node and all its following nodes."""
|
2020-10-05 11:08:57 +00:00
|
|
|
string_rep = []
|
2019-11-10 08:47:04 +00:00
|
|
|
temp = self
|
|
|
|
while temp:
|
2020-10-05 11:08:57 +00:00
|
|
|
string_rep.append(f"{temp.data}")
|
2019-11-10 08:47:04 +00:00
|
|
|
temp = temp.next
|
2020-10-05 11:08:57 +00:00
|
|
|
return "->".join(string_rep)
|
2019-11-10 08:47:04 +00:00
|
|
|
|
|
|
|
|
2020-10-05 11:08:57 +00:00
|
|
|
def make_linked_list(elements_list: List):
|
2019-11-10 08:47:04 +00:00
|
|
|
"""Creates a Linked List from the elements of the given sequence
|
2020-10-05 11:08:57 +00:00
|
|
|
(list/tuple) and returns the head of the Linked List.
|
|
|
|
>>> make_linked_list([])
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
Exception: The Elements List is empty
|
|
|
|
>>> make_linked_list([7])
|
|
|
|
7
|
|
|
|
>>> make_linked_list(['abc'])
|
|
|
|
abc
|
|
|
|
>>> make_linked_list([7, 25])
|
|
|
|
7->25
|
|
|
|
"""
|
2019-11-10 08:47:04 +00:00
|
|
|
if not elements_list:
|
|
|
|
raise Exception("The Elements List is empty")
|
|
|
|
|
2020-10-05 11:08:57 +00:00
|
|
|
current = head = Node(elements_list[0])
|
|
|
|
for i in range(1, len(elements_list)):
|
|
|
|
current.next = Node(elements_list[i])
|
2019-11-10 08:47:04 +00:00
|
|
|
current = current.next
|
|
|
|
return head
|
|
|
|
|
2019-11-14 18:59:43 +00:00
|
|
|
|
2020-10-05 11:08:57 +00:00
|
|
|
def print_reverse(head_node: Node) -> None:
|
|
|
|
"""Prints the elements of the given Linked List in reverse order
|
|
|
|
>>> print_reverse([])
|
|
|
|
>>> linked_list = make_linked_list([69, 88, 73])
|
|
|
|
>>> print_reverse(linked_list)
|
|
|
|
73
|
|
|
|
88
|
|
|
|
69
|
|
|
|
"""
|
|
|
|
if head_node is not None and isinstance(head_node, Node):
|
2019-11-10 08:47:04 +00:00
|
|
|
print_reverse(head_node.next)
|
|
|
|
print(head_node.data)
|
|
|
|
|
|
|
|
|
2020-10-05 11:08:57 +00:00
|
|
|
def main():
|
|
|
|
from doctest import testmod
|
|
|
|
|
|
|
|
testmod()
|
|
|
|
|
|
|
|
linked_list = make_linked_list([14, 52, 14, 12, 43])
|
|
|
|
print("Linked List:")
|
|
|
|
print(linked_list)
|
|
|
|
print("Elements in Reverse:")
|
|
|
|
print_reverse(linked_list)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|