Skip to content

Commit 2579203

Browse files
committed
Add py stack
1 parent 1477e20 commit 2579203

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

python/data_structures/p233_stack.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
'''
2+
CLRS Section 10.1, p. 233
3+
'''
4+
5+
class Stack:
6+
def __init__(self, S=None, top=-1):
7+
if S is None:
8+
self.S = []
9+
else:
10+
self.S = S
11+
self.top = top
12+
13+
def stack_empty(self):
14+
return self.top == -1
15+
16+
def push(self, x):
17+
self.top += 1
18+
self.S[self.top] = x
19+
20+
def pop(self):
21+
if self.stack_empty():
22+
raise Exception('underflow')
23+
else:
24+
self.top -= 1
25+
self.S.append(None)
26+
return self.S.pop(self.top + 1)

python/main.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,3 +169,26 @@
169169
print('\nafter build_min_heap:', min_pq.A)
170170
min_pq.min_heap_insert(6)
171171
print('after min_heap_insert(6):', min_pq.A)
172+
173+
# CLRS Section 10.1 - Stack
174+
from data_structures.p233_stack import Stack
175+
176+
print('\nSection 10.1 - Stack')
177+
178+
S = Stack([15, 6, 2, 9, None, None, None], 3) # cf. Figure 10.1, p. 233
179+
S.push(17)
180+
S.push(3)
181+
print('\nafter push(17), push(3):', S.S)
182+
S.pop()
183+
print('after pop():', S.S)
184+
185+
S = Stack([None for elements in range(0, 6)]) # cf. Exercise 10.1-1, p. 235
186+
S.push(4)
187+
S.push(1)
188+
S.push(3)
189+
print('\nafter push(4), push(1), push(3):', S.S)
190+
S.pop()
191+
S.push(8)
192+
print('after pop(), push(8):', S.S)
193+
S.pop()
194+
print('after pop():', S.S)

0 commit comments

Comments
 (0)