Skip to content

Commit 5869fda

Browse files
cclaussgithub-actions
and
github-actions
authored
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>
1 parent cffdf99 commit 5869fda

File tree

2 files changed

+101
-40
lines changed

2 files changed

+101
-40
lines changed

Diff for: DIRECTORY.md

+6-1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
* [Index Of Rightmost Set Bit](bit_manipulation/index_of_rightmost_set_bit.py)
5151
* [Is Even](bit_manipulation/is_even.py)
5252
* [Is Power Of Two](bit_manipulation/is_power_of_two.py)
53+
* [Largest Pow Of Two Le Num](bit_manipulation/largest_pow_of_two_le_num.py)
5354
* [Missing Number](bit_manipulation/missing_number.py)
5455
* [Numbers Different Signs](bit_manipulation/numbers_different_signs.py)
5556
* [Reverse Bits](bit_manipulation/reverse_bits.py)
@@ -322,6 +323,7 @@
322323
* [Integer Partition](dynamic_programming/integer_partition.py)
323324
* [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py)
324325
* [Knapsack](dynamic_programming/knapsack.py)
326+
* [Largest Divisible Subset](dynamic_programming/largest_divisible_subset.py)
325327
* [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py)
326328
* [Longest Common Substring](dynamic_programming/longest_common_substring.py)
327329
* [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py)
@@ -460,6 +462,7 @@
460462
## Greedy Methods
461463
* [Fractional Knapsack](greedy_methods/fractional_knapsack.py)
462464
* [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py)
465+
* [Gas Station](greedy_methods/gas_station.py)
463466
* [Minimum Waiting Time](greedy_methods/minimum_waiting_time.py)
464467
* [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py)
465468

@@ -542,6 +545,7 @@
542545
* [Average Median](maths/average_median.py)
543546
* [Average Mode](maths/average_mode.py)
544547
* [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py)
548+
* [Base Neg2 Conversion](maths/base_neg2_conversion.py)
545549
* [Basic Maths](maths/basic_maths.py)
546550
* [Bell Numbers](maths/bell_numbers.py)
547551
* [Binary Exp Mod](maths/binary_exp_mod.py)
@@ -657,7 +661,6 @@
657661
* [P Series](maths/series/p_series.py)
658662
* [Sieve Of Eratosthenes](maths/sieve_of_eratosthenes.py)
659663
* [Sigmoid](maths/sigmoid.py)
660-
* [Sigmoid Linear Unit](maths/sigmoid_linear_unit.py)
661664
* [Signum](maths/signum.py)
662665
* [Simpson Rule](maths/simpson_rule.py)
663666
* [Simultaneous Linear Equation Solver](maths/simultaneous_linear_equation_solver.py)
@@ -716,6 +719,7 @@
716719
* [Leaky Rectified Linear Unit](neural_network/activation_functions/leaky_rectified_linear_unit.py)
717720
* [Rectified Linear Unit](neural_network/activation_functions/rectified_linear_unit.py)
718721
* [Scaled Exponential Linear Unit](neural_network/activation_functions/scaled_exponential_linear_unit.py)
722+
* [Sigmoid Linear Unit](neural_network/activation_functions/sigmoid_linear_unit.py)
719723
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
720724
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
721725
* [Perceptron](neural_network/perceptron.py)
@@ -1180,6 +1184,7 @@
11801184
* [Naive String Search](strings/naive_string_search.py)
11811185
* [Ngram](strings/ngram.py)
11821186
* [Palindrome](strings/palindrome.py)
1187+
* [Pig Latin](strings/pig_latin.py)
11831188
* [Prefix Function](strings/prefix_function.py)
11841189
* [Rabin Karp](strings/rabin_karp.py)
11851190
* [Remove Duplicate](strings/remove_duplicate.py)

Diff for: data_structures/linked_list/print_reverse.py

+95-39
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,91 @@
11
from __future__ import annotations
22

3+
from collections.abc import Iterable, Iterator
4+
from dataclasses import dataclass
35

6+
7+
@dataclass
48
class Node:
5-
def __init__(self, data=None):
6-
self.data = data
7-
self.next = None
9+
data: int
10+
next_node: Node | None = None
11+
12+
13+
class LinkedList:
14+
"""A class to represent a Linked List.
15+
Use a tail pointer to speed up the append() operation.
16+
"""
17+
18+
def __init__(self) -> None:
19+
"""Initialize a LinkedList with the head node set to None.
20+
>>> linked_list = LinkedList()
21+
>>> (linked_list.head, linked_list.tail)
22+
(None, None)
23+
"""
24+
self.head: Node | None = None
25+
self.tail: Node | None = None # Speeds up the append() operation
26+
27+
def __iter__(self) -> Iterator[int]:
28+
"""Iterate the LinkedList yielding each Node's data.
29+
>>> linked_list = LinkedList()
30+
>>> items = (1, 2, 3, 4, 5)
31+
>>> linked_list.extend(items)
32+
>>> tuple(linked_list) == items
33+
True
34+
"""
35+
node = self.head
36+
while node:
37+
yield node.data
38+
node = node.next_node
39+
40+
def __repr__(self) -> str:
41+
"""Returns a string representation of the LinkedList.
42+
>>> linked_list = LinkedList()
43+
>>> str(linked_list)
44+
''
45+
>>> linked_list.append(1)
46+
>>> str(linked_list)
47+
'1'
48+
>>> linked_list.extend([2, 3, 4, 5])
49+
>>> str(linked_list)
50+
'1 -> 2 -> 3 -> 4 -> 5'
51+
"""
52+
return " -> ".join([str(data) for data in self])
853

9-
def __repr__(self):
10-
"""Returns a visual representation of the node and all its following nodes."""
11-
string_rep = []
12-
temp = self
13-
while temp:
14-
string_rep.append(f"{temp.data}")
15-
temp = temp.next
16-
return "->".join(string_rep)
54+
def append(self, data: int) -> None:
55+
"""Appends a new node with the given data to the end of the LinkedList.
56+
>>> linked_list = LinkedList()
57+
>>> str(linked_list)
58+
''
59+
>>> linked_list.append(1)
60+
>>> str(linked_list)
61+
'1'
62+
>>> linked_list.append(2)
63+
>>> str(linked_list)
64+
'1 -> 2'
65+
"""
66+
if self.tail:
67+
self.tail.next_node = self.tail = Node(data)
68+
else:
69+
self.head = self.tail = Node(data)
1770

71+
def extend(self, items: Iterable[int]) -> None:
72+
"""Appends each item to the end of the LinkedList.
73+
>>> linked_list = LinkedList()
74+
>>> linked_list.extend([])
75+
>>> str(linked_list)
76+
''
77+
>>> linked_list.extend([1, 2])
78+
>>> str(linked_list)
79+
'1 -> 2'
80+
>>> linked_list.extend([3,4])
81+
>>> str(linked_list)
82+
'1 -> 2 -> 3 -> 4'
83+
"""
84+
for item in items:
85+
self.append(item)
1886

19-
def make_linked_list(elements_list: list):
87+
88+
def make_linked_list(elements_list: Iterable[int]) -> LinkedList:
2089
"""Creates a Linked List from the elements of the given sequence
2190
(list/tuple) and returns the head of the Linked List.
2291
>>> make_linked_list([])
@@ -28,43 +97,30 @@ def make_linked_list(elements_list: list):
2897
>>> make_linked_list(['abc'])
2998
abc
3099
>>> make_linked_list([7, 25])
31-
7->25
100+
7 -> 25
32101
"""
33102
if not elements_list:
34103
raise Exception("The Elements List is empty")
35104

36-
current = head = Node(elements_list[0])
37-
for i in range(1, len(elements_list)):
38-
current.next = Node(elements_list[i])
39-
current = current.next
40-
return head
105+
linked_list = LinkedList()
106+
linked_list.extend(elements_list)
107+
return linked_list
41108

42109

43-
def print_reverse(head_node: Node) -> None:
110+
def in_reverse(linked_list: LinkedList) -> str:
44111
"""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
112+
>>> in_reverse(LinkedList())
113+
''
114+
>>> in_reverse(make_linked_list([69, 88, 73]))
115+
'73 <- 88 <- 69'
51116
"""
52-
if head_node is not None and isinstance(head_node, Node):
53-
print_reverse(head_node.next)
54-
print(head_node.data)
117+
return " <- ".join(str(line) for line in reversed(tuple(linked_list)))
55118

56119

57-
def main():
120+
if __name__ == "__main__":
58121
from doctest import testmod
59122

60123
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()
124+
linked_list = make_linked_list((14, 52, 14, 12, 43))
125+
print(f"Linked List: {linked_list}")
126+
print(f"Reverse List: {in_reverse(linked_list)}")

0 commit comments

Comments
 (0)