Skip to content

Commit cf9785c

Browse files
Add python linked stack impl.
1 parent 591e5ed commit cf9785c

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

linked_stack/linked_stack.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from typing import Optional
2+
3+
4+
class Element:
5+
6+
def __init__(self, value: int) -> None:
7+
self.value = value
8+
self.next = None
9+
10+
def __str__(self) -> str:
11+
return f'<Element(value={self.value})>'
12+
13+
14+
class LinkedStack:
15+
16+
def __init__(self, head: Optional[Element] = None) -> None:
17+
self.head = head
18+
19+
def __str__(self) -> str:
20+
current_element = self.head
21+
elements = []
22+
while current_element.next:
23+
elements.append(str(current_element))
24+
current_element = current_element.next
25+
elements.append(str(current_element))
26+
return str(elements)
27+
28+
def push(self, new_element: Element) -> None:
29+
if self.head is None:
30+
self.head = new_element
31+
else:
32+
new_element.next = self.head
33+
self.head = new_element
34+
35+
def pop(self) -> Element:
36+
old_head = self.head
37+
self.head = old_head.next
38+
return old_head
39+
40+
41+
if __name__ == "__main__":
42+
first_el = Element(1)
43+
second_el = Element(2)
44+
third_el = Element(3)
45+
46+
linked_stack = LinkedStack(first_el)
47+
linked_stack.push(second_el)
48+
linked_stack.push(third_el)
49+
50+
assert linked_stack.pop() is third_el

0 commit comments

Comments
 (0)