-
Notifications
You must be signed in to change notification settings - Fork 73
/
Stacks.py
120 lines (60 loc) · 2.27 KB
/
Stacks.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#Language: Python
#Github: https://github.com/Divyaantkj01
#Menu Driven Program to perform stack operations
Stack=list() # A default stack using list() function.
top=-1 # To know the current index position in stack.
#Adding element into a stack.
def Push_element(Stack,top):
Ch='Y'
while Ch == 'Y' or Ch == 'y'or Ch == 'Yes':
val=input("Enter the value to be added in the stack: ")
Stack.append(val) # Adding element into stack list.
top += 1 # It checks the total number of addition.
print ("Do you want to add more...<y/n>: ", end="")
Ch = input()
if Ch == 'N' or Ch == 'n' or Ch == 'No' or Ch == 'NO':
break
return top
#Removing stack elements
def Pop_element(Stack, top):
slen = len(Stack) # Finds total elements in the stack.
if slen <= 0: # Checks if stack is empty or not.
print("Stack is empty")
else:
val = Stack.pop() # Removing from top of the stack.
top = top-1
print("Value deleted from stack is", val)
return top
# Showing stack elements
def Show_element(Stack, top):
slen = len(Stack) # Finds total elements in the stack.
if slen <= 0: # Checks if stack is empty or not.
print ("Stack is empty")
else:
print("The stack elements are...")
i= top
while (i >= 0): # Stack elements processed in reverse order.
print(Stack[i])
i-=1
while (True):
print()
print ('STACK OPERATION')
print ('-----------------')
print ('1. Adding elements to a stack')
print ('2. Removing elements from a stack')
print ('3. Showing elements of a stack')
print ('4. Exit from stack operation')
print()
Opt= int(input( "Enter your option: "))
print()
if (Opt == 1):
#Push operation of stack - Adding element at top of the stack
top = Push_element(Stack, top)
elif (Opt == 2):
#Pop operation of stack - Deleting element
top = Pop_element(Stack, top)
elif (Opt==3):
# Traversing / Showing stack element
Show_element(Stack,top)
elif (Opt==4):
break