mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-07-06 18:49:26 +08:00
print reverse: A LinkedList with a tail pointer (#9875)
* print reverse: A LinkedList with a tail pointer * updating DIRECTORY.md --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
@ -1,22 +1,91 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Iterator
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
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."""
|
||||
string_rep = []
|
||||
temp = self
|
||||
while temp:
|
||||
string_rep.append(f"{temp.data}")
|
||||
temp = temp.next
|
||||
return "->".join(string_rep)
|
||||
data: int
|
||||
next_node: Node | None = None
|
||||
|
||||
|
||||
def make_linked_list(elements_list: list):
|
||||
class LinkedList:
|
||||
"""A class to represent a Linked List.
|
||||
Use a tail pointer to speed up the append() operation.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Initialize a LinkedList with the head node set to None.
|
||||
>>> linked_list = LinkedList()
|
||||
>>> (linked_list.head, linked_list.tail)
|
||||
(None, None)
|
||||
"""
|
||||
self.head: Node | None = None
|
||||
self.tail: Node | None = None # Speeds up the append() operation
|
||||
|
||||
def __iter__(self) -> Iterator[int]:
|
||||
"""Iterate the LinkedList yielding each Node's data.
|
||||
>>> linked_list = LinkedList()
|
||||
>>> items = (1, 2, 3, 4, 5)
|
||||
>>> linked_list.extend(items)
|
||||
>>> tuple(linked_list) == items
|
||||
True
|
||||
"""
|
||||
node = self.head
|
||||
while node:
|
||||
yield node.data
|
||||
node = node.next_node
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""Returns a string representation of the LinkedList.
|
||||
>>> linked_list = LinkedList()
|
||||
>>> str(linked_list)
|
||||
''
|
||||
>>> linked_list.append(1)
|
||||
>>> str(linked_list)
|
||||
'1'
|
||||
>>> linked_list.extend([2, 3, 4, 5])
|
||||
>>> str(linked_list)
|
||||
'1 -> 2 -> 3 -> 4 -> 5'
|
||||
"""
|
||||
return " -> ".join([str(data) for data in self])
|
||||
|
||||
def append(self, data: int) -> None:
|
||||
"""Appends a new node with the given data to the end of the LinkedList.
|
||||
>>> linked_list = LinkedList()
|
||||
>>> str(linked_list)
|
||||
''
|
||||
>>> linked_list.append(1)
|
||||
>>> str(linked_list)
|
||||
'1'
|
||||
>>> linked_list.append(2)
|
||||
>>> str(linked_list)
|
||||
'1 -> 2'
|
||||
"""
|
||||
if self.tail:
|
||||
self.tail.next_node = self.tail = Node(data)
|
||||
else:
|
||||
self.head = self.tail = Node(data)
|
||||
|
||||
def extend(self, items: Iterable[int]) -> None:
|
||||
"""Appends each item to the end of the LinkedList.
|
||||
>>> linked_list = LinkedList()
|
||||
>>> linked_list.extend([])
|
||||
>>> str(linked_list)
|
||||
''
|
||||
>>> linked_list.extend([1, 2])
|
||||
>>> str(linked_list)
|
||||
'1 -> 2'
|
||||
>>> linked_list.extend([3,4])
|
||||
>>> str(linked_list)
|
||||
'1 -> 2 -> 3 -> 4'
|
||||
"""
|
||||
for item in items:
|
||||
self.append(item)
|
||||
|
||||
|
||||
def make_linked_list(elements_list: Iterable[int]) -> LinkedList:
|
||||
"""Creates a Linked List from the elements of the given sequence
|
||||
(list/tuple) and returns the head of the Linked List.
|
||||
>>> make_linked_list([])
|
||||
@ -28,43 +97,30 @@ def make_linked_list(elements_list: list):
|
||||
>>> make_linked_list(['abc'])
|
||||
abc
|
||||
>>> make_linked_list([7, 25])
|
||||
7->25
|
||||
7 -> 25
|
||||
"""
|
||||
if not elements_list:
|
||||
raise Exception("The Elements List is empty")
|
||||
|
||||
current = head = Node(elements_list[0])
|
||||
for i in range(1, len(elements_list)):
|
||||
current.next = Node(elements_list[i])
|
||||
current = current.next
|
||||
return head
|
||||
linked_list = LinkedList()
|
||||
linked_list.extend(elements_list)
|
||||
return linked_list
|
||||
|
||||
|
||||
def print_reverse(head_node: Node) -> None:
|
||||
def in_reverse(linked_list: LinkedList) -> str:
|
||||
"""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
|
||||
>>> in_reverse(LinkedList())
|
||||
''
|
||||
>>> in_reverse(make_linked_list([69, 88, 73]))
|
||||
'73 <- 88 <- 69'
|
||||
"""
|
||||
if head_node is not None and isinstance(head_node, Node):
|
||||
print_reverse(head_node.next)
|
||||
print(head_node.data)
|
||||
|
||||
|
||||
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)
|
||||
return " <- ".join(str(line) for line in reversed(tuple(linked_list)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
from doctest import testmod
|
||||
|
||||
testmod()
|
||||
linked_list = make_linked_list((14, 52, 14, 12, 43))
|
||||
print(f"Linked List: {linked_list}")
|
||||
print(f"Reverse List: {in_reverse(linked_list)}")
|
||||
|
Reference in New Issue
Block a user