-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDS STACK.py
87 lines (69 loc) · 1.87 KB
/
DS STACK.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
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
75
76
77
78
79
80
81
82
83
84
85
86
87
S=[] #stack
top=None
def isEmpty(stk):
"Returns if a stack is empty or not"
# return stk==[]
if stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk)-1
def s_pop(stk):
if isEmpty(stk):
return "Underflow"
else:
i = stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return i
def peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top=len(stk)-1
return stk[top]
def display(stk):
if isEmpty(stk):
print("Underflow")
else:
top=len(stk)-1
print(stk[top],"<----TOP")
for i in range(top-1,-1,-1):
print(stk[i])
if __name__=="__main__":
while True:
print("STACK IMPLEMENTATION")
print("1.PUSH")
print("2.POP")
print("3.DISPLAY")
print("4.PEEK")
print("5.EXIT")
chs=[1,2,3,4,5]
ch=int(input("Enter your choice(1-5):\n"))
if ch in chs:
if ch==1:
i=int(input("Enter your number:\n"))
push(S,i)
print(f"succesfully pushed {i}")
input("press any key to continue")
elif ch==2:
# i=int(input("Enter your number:\n"))/
item=s_pop(S)
if item=="Underflow":
print("Underflow ! cannot pop the stack")
else:
print(f"succesfully popped {item}" )
input("press any key to continue")
elif ch==3:
# i=int(input("Enter your number:\n"))
display(S)
input("press any key to continue")
elif ch == 4:
print(peek(S))
input("press any key to continue")
elif ch == 5:
quit()