Stack
A stack is a linear/sequential data structure in which insertion and deletion can take place at one end i.e. stack top. Stack is LIFO data structure i.e. Last In First Out
- Operation that can be performed on stack are:
- PUSH: When a new element/item is added to the top of the stack, its called PUSH
- POP: When a new element/item is removed from the top of the stack, its called POP
- TRAVERSAL: Display the complete stack items
Implementation of stack using LIST:
In [1]:
#Creating a STACK
stack=list()
stack=[]
In [3]:
#Adding Element to the STACK
list.append()
In [ ]:
#Deleting an item from STACK
list.pop()
list.pop([i])
In [ ]:
# Program to implement a stack with LIST
stack=[]
c='y'
while (c=='y'):
print("1. PUSH")
print("2. POP")
print("3. Display")
choice=int(input("Enter your choices: "))
if (choice==1):
a=input("Enter any number: ")
stack.append(a)
elif (choice==2):
if (stack==[]):
print("Stack Empty")
else:
print("Deleted element is :", stack.pop())
elif (choice==3):
l=len(stack)
for i in range(l-1,-1,-1):
print(stack[i])
else:
print("wrong input")
c=input("Do you want to continue or not? ")
Application of Stacks:
- The copy,paste function is implemented using stack
- The redo, undo is implemented using stack
- Stack are used to avoid the use of operator precedence in multioperator operation expression evaluation
- The compilers use stack to store the previous state of a program wehn a function is called or during recursion
Assignment:
- Write a program to display unique vowels present in the given word using stack
- Write a program to add, delete and display the records of an employee using list using stack
CBSE Question:
- Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list push all numbers divisible by 5 into a stack implemented by using a list. Display the stack if it has at least one element, otherwise display appropriate error message.
In [4]:
def push(arr):
stack=[]
for i in arr:
if i%5==0:
stack.append(i)
if stack==[]:
print("The stack is empty")
else:
for i in range(len(stack)-1,-1,-1):
print(stack[i])
push([15,47,48,9,5,12,10])
In [ ]: