-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
74 lines (62 loc) · 1.15 KB
/
stack.py
File metadata and controls
74 lines (62 loc) · 1.15 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
65
66
67
68
69
70
71
72
73
74
#stack1 is non-classified version
STKSIZE=3
ptr= -1
def push(stk,x):
global ptr
global STKSIZE
if ptr<STKSIZE-1:
ptr+=1
stk[ptr]=x
return stk
else:
print('stack overflow')
def pop(stk):
global ptr
if ptr>-1:
s=stk[ptr]
ptr-=1
return s
else:
print('stack empty')
stack1=[None]*STKSIZE
push(stack1,1)
push(stack1,2)
push(stack1,3)
push(stack1,4)
print(pop(stack1))
print(pop(stack1))
print(pop(stack1))
print(pop(stack1))
#stack2 is classified version
class Stack:
def __init__(self,size=3):
self.ptr=-1
self.size=size
self.stk=[None]*size
def isEmpty(self):
return self.ptr == -1 # ptr<0
def isFull(self):
return self.ptr == self.size-1 #ptr>size-2
def push(self,x):
if self.isFull():
print('stack overflow')
else:
self.ptr+=1
self.stk[self.ptr]=x
return self
def pop(self):
if self.isEmpty():
print('stack empty')
else:
s=self.stk[self.ptr]
self.ptr-=1
return s
stack2=Stack(3)
stack2.push(1)
stack2.push(2)
stack2.push(3)
stack2.push(4)
print(stack2.pop())
print(stack2.pop())
print(stack2.pop())
print(stack2.pop())