Skip to content

Commit 93b7734

Browse files
committed
add: dynamic stack in python
1 parent 28bf41e commit 93b7734

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

src/python/dynamic_stack.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Stack: Last In - First Out (LIFO)
2+
3+
# Define node format: value and a pointier to next
4+
class Node:
5+
def __init__(self, value: int) -> None:
6+
self.value = value
7+
self.next = None
8+
9+
10+
class DynamicStack:
11+
def __init__(self) -> None:
12+
self.__first = None
13+
14+
def isEmpty(self) -> bool:
15+
if not self.__first:
16+
return True
17+
return False
18+
19+
def push(self,value: int):
20+
node = Node(value)
21+
node.next = self.__first
22+
self.__first = node
23+
24+
def pop(self) -> int:
25+
if self.isEmpty():
26+
raise Exception('Stack is empty!')
27+
removedElement = self.__first.value
28+
self.__first = self.__first.next
29+
return removedElement
30+
31+
32+
def show(self) -> None:
33+
node = self.__first
34+
print('[', end=' ')
35+
while(node):
36+
print(node.value, end=' ')
37+
node = node.next
38+
print(']')
39+
40+
def main() -> None:
41+
dynamic_stack = DynamicStack()
42+
43+
print(f'Push(1,2,4):')
44+
dynamic_stack.push(1)
45+
dynamic_stack.push(2)
46+
dynamic_stack.push(4)
47+
48+
dynamic_stack.show()
49+
50+
print(f'Remove last: {dynamic_stack.pop()}')
51+
print(f'Remove last: {dynamic_stack.pop()}')
52+
print(f'Remove last: {dynamic_stack.pop()}')
53+
print('Empty stack!')
54+
dynamic_stack.show()
55+
56+
if __name__ == "__main__":
57+
main()

0 commit comments

Comments
 (0)