-
Notifications
You must be signed in to change notification settings - Fork 5
/
stackwithdynamicarray.py
45 lines (40 loc) · 1.15 KB
/
stackwithdynamicarray.py
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
# Creating a stack with dynamic array which doubles its size if shortage of space
class StackWithDynamicArray:
def __init__(self):
self.length = 0
self.capacity = 1
self.stack = [None]*self.capacity
self.top = 0
# Method to push into stack
# @@Param: data
def push(self,data):
if self.length == self.capacity:
new_stack = self.stack + [None]*self.capacity
self.stack = new_stack
self.capacity = len(self.stack)
self.stack[self.top] = data
self.top+=1
self.length+=1
# Method to pop from stack
def pop(self):
if self.length==0:
raise ValueError("UnderFlow")
retValue = self.stack[self.top-1]
self.stack[self.top-1] = None
self.top-=1
return retValue
def __str__(self):
retValue = ""
for data in self.stack:
retValue+="{}|".format(data)
return retValue
def main():
dStack = StackWithDynamicArray()
dStack.push(3)
dStack.push(4)
dStack.push(5)
dStack.push(6)
dStack.push(7)
dStack.pop()
print(dStack)
main()