DATA STRUCTURE -STACK
• A data structure defines a mechanism to store, organise and access data
along with operations (processing) that can be efficiently performed on
the data.
• For example, string is a data structure containing a sequence of elements
where each element is a character.
• On the other hand, list is a sequence data structure in which each
element may be of different types.
• We can apply different operations like reversal, slicing, counting of
elements, etc. on list and string. Hence, a data structure organises multiple
elements in a way so that certain operations on each element as well as
the collective data unit could be performed easily.
• Stack and Queue are two other popular data structures used in
programming.
APPLICATIONS OF STACK
Some of the applications of stack in real-life are:
• Pile of clothes in an almirah
• Multiple chairs in a vertical pile
• Bangles worn on wrist
• Pile of boxes of eatables in pantry or on a kitchen shelf
Application of Stack in Programming
• Reversing the string
• redo/undo option in text editors
• While browsing the web, we move from one web page
to another by accessing links between them.The history of browsed pages is maintained as
stack.
• While writing any arithmetic expression in a program, order of evaluation of arithmetic
operators is maintained by stack.
Key Operations in stacks:
Push: Add an element to the top of the stack.
Pop: Remove the top element from the stack.
Peek: View the top element without removing it.
isEmpty: Check if the stack is empty.
Stacks in python are a dynamic data structure as they can grow (with
increase in number of elements) or shrink (with decrease in number of
elements). A static data structure, on the other hand, is the one that has
fixed size.
For various stack operations, we can use a list say stack and use python code as
described below:
Peek we can use: <stack> [top]
where < stack> is a list; top is an integer having value equal to len (<stack>) -1.
Push we can use: <stack>. append (<item>)
when <item> is the item being pushed in the stack.
Pop we can use: <stack>. Pop ( )
it removes the last value from the stack and returns it.
Example stack program with list of number .Initially stack is empty
def isEmpty (stk):
if stk == [ ]
return True
else:
returns False
def push (stk, item) :
stk. append (item)
top = len (stk) -1
Example stack program with list of number .Intially stack is empty
def pop (stk):
if is Empty (stk) :
return “underflow”
else:
item = stk. Pop ( )
if len (stk) == 0:
top = None
else:
top = len (stk) -1
return item
Example stack program with list of number .Initially stack is empty
def peek (stk) :
if is Empty (stk) :
return “underflow”
else:
top = len (stk) -1
return stk [top]
Example stack program with list of number . Initially stack is empty
def Display (stk) :
if is Empty (stk) :
print (:stack empty”)
else:
top = len (stk) -1
print (stk[top], “<- top” )
for a in range (top- 1, -1, -1 ) :
print (stk [a])
Example stack program with list of number . Initially stack is empty
stack = [ ] #
initially stack is empty
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)
Example stack program with list of number . Initially stack is empty
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!” )
A School has created a dictionary containing top players and their runs as key value
pairs of cricket team. Write a program with separate user defined functions to perform
the following operations:
(a) Push the name of the players(Keys) of the dictionary into a stack, where the
corresponding runs (value) is greater than 49.
(b) Pop and display the content of the stack.
For Example
If dictionary has the following values:
Data={'Rohan':40, 'Rihaan':55, 'Tejas':80,'Ajay':90}
The output should be:
Ajay
Tejas
Rihaan
# Function to push player names with runs > 49 into a stack
def push_players(data):
for player, runs in data.items():
if runs > 49:
stack.append(player)
return stack
# Function to pop and display contents of the stack
def pop_stack():
print("\nTop players (runs > 49):")
while stack !=[]:
print(stack.pop())
else:
print(“stack Empty”)
Stack=[]
data = {}
n = int(input("Enter number of players: "))
for i in range(n):
name = input("Enter name of player : ")
runs = int(input("Enter runs scored : "))
data[name] = runs
push_players(data)
pop_stack()
Board question
Board question
Board question
Priyanka has created a dictionary 'emeployee_data' containing EmpCode and Salary as key
value pairs for 5 Employees of Cyber Intratech. Write a program, With separate user defined
function, as mentioned below, to perform the following operations:
(a) push_emp(): Push all those EmpCode, where the Salary is less than 25000, from the
dictionary into a stack 'stk_emp'
(b) pop_emp(): Remove all the elements from the stack, one at a time, in a Last-In-First-
Out(LIFO) manner and displays them. It also displays 'Stack is empty' once all the element
have been removed.
For Example:
If the sample content of the dictionary is as follows:
{'E001':15000,'E002':27000,'E003':30000,'E004':15000,'E005':19000}, then the stack
'stk_emp' will contain EmpCode E001, E004, E005 after push_emp(). pop_emp() will pop and
display employee record in LIFO fashion and display 'Stack is empty' at last.