forked from satojkovic/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
64 lines (52 loc) · 1.32 KB
/
Copy pathstack.py
File metadata and controls
64 lines (52 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class ListNode:
def __init__(self, data):
self.data = data
self.next = None
# Stack implemented by linked list
class Stack:
def __init__(self):
self.top = None
def is_empty(self):
return not self.top
def pop(self):
if self.is_empty():
return None
ret = self.top.data
self.top = self.top.next
return ret
def push(self, data):
node = ListNode(data)
node.next = self.top
self.top = node
def peek(self):
return self.top.data if not self.is_empty() else None
def print_stack(self):
if self.is_empty():
print('Stack is empty.')
return
print('Current Stack:')
node = self.top
while node:
print(node.data)
node = node.next
class StackByList:
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
def push(self, data):
self.stack.append(data)
def pop(self):
if self.is_empty():
return None
# Pop last: O(1)
return self.stack.pop()
if __name__ == "__main__":
stack = StackByList()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())