-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstacks.py
More file actions
69 lines (63 loc) · 1.45 KB
/
stacks.py
File metadata and controls
69 lines (63 loc) · 1.45 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
def isEmpty(stk):
if stk==[]:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack empty")
else:
top=len(stk)-1
print(stk[top],"<- top")
for a in range(top-1,-1,-1):
print(stk[a])
Stack=[]
top=None
while True:
print("Stack Operations")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display stack")
print("5. Exit")
ch=int(input("Enter your choice(1-5)"))
if ch==1:
item=int(input("Enter item"))
Push(Stack,item)
elif ch==2:
item=Pop(Stack)
if item=="Underflow":
print("Underflow, Stack is empty")
else:
print("Popped item is",item)
elif ch==3:
item=Peek(Stack)
if item=="Underflow":
print("Underflow, Stack is empty")
else:
print("Topmost item is ",item)
elif ch==4:
Display(Stack)
elif ch==5:
break
else:
print("Invalid Choice")