0% found this document useful (0 votes)
167 views

Stack

The document discusses data structures and stacks. It defines a stack as a linear data structure that follows the LIFO (Last-In First-Out) principle, where elements can only be inserted or removed from one end called the top of the stack. Some key characteristics of stacks are discussed, along with examples like piles of books. Common stack operations like PUSH and POP are described. Implementing stacks using lists in Python is demonstrated, including adding/pushing elements and removing/popping elements from the stack. Several programming problems involving stacks are provided with sample solutions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
167 views

Stack

The document discusses data structures and stacks. It defines a stack as a linear data structure that follows the LIFO (Last-In First-Out) principle, where elements can only be inserted or removed from one end called the top of the stack. Some key characteristics of stacks are discussed, along with examples like piles of books. Common stack operations like PUSH and POP are described. Implementing stacks using lists in Python is demonstrated, including adding/pushing elements and removing/popping elements from the stack. Several programming problems involving stacks are provided with sample solutions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Data Structure

Data + Structure
Data Structure is a way of collecting and organizing data in such a way that we can
perform operations on these data in an effective way.

Stack
** Stack is a linear data structure.
It is a user-defined or non-primitive data structure.

A stack is a data structure whose elements are accessed according to the Last-In
First-Out (LIFO) principle. This is because in a stack, insertion and deletion of
elements can only take place at one end, called top of the stack.

Linear Data Structure:


A data structure in which elements are organised in a sequence is called linear data
structure.

Consider the following examples of stack:


1. A pile of books
2. A stack of coins
3. Ten glass plates placed one above another.

The two operations performed on the stack are:

 PUSH
 POP
Implementing stack using list

Push operation: It means inserting element at the top of the stack. This can be done
with the help of append() method of the list as: st.append(element) where ‘st’ is a
list.

Pop operation: It means removing the topmost element from the stack. This can be
performed using pop() method of the list as: st.pop() where ‘st’ is a list. This method
returns the removed element that can be displayed.
** Pushing an element into stack already having five elements and stack size of 5,
then it is stack overflow. This condition is applicable to static stack.
** In a stack if user tries to remove element from empty stack it is stack underflow.
Give any two characteristics of stacks
Characteristics of Stacks:
 It is a LIFO data structure
 The insertion and deletion happens at one end i.e. from the top of the stack

Applications of Stack
Recursion
Reversing a string
Undo mechanism in text editors

Programs:

1. Write a Python program to implement a stack using list.

Source Code:
# Implementation of stack using list
st=[] #to create an empty list
def stkpush():
n=int(input("Enter a No. : "))
st.append(n)

def stkpop():
if st==[]: # if len(st)==0:
print("Stack Underflow/Stack is Empty")
else:
print(st.pop()," removed")
def display():
if st==[ ]:
print("Stack Underflow/Stack is empty")
else:
print("STACK CONTENTS: ")
L=len(st)-1
for i in range(L,-1,-1):
print(st[i])

while True:
print('***STACK DEMONSTRATION***')
print('***1. PUSH***')
print('***2. POP***')
print('***3. DISPLAY***')
choice=int(input('Enter your choice (1-3) to continue and other than (1-3) to
Exit'))
if choice==1:
stkpush()
elif choice==2:
stkpop()
elif choice==3:
display()
else:
print('Wrong choice')
break
2. Write a Python program to display unique vowels and the total number of
unique vowels present in the given word using Stack (implemented as list).

Source Code:
vowels=['a','e','i','o','u']
word=input('Enter the word to search for vowels:')
Stack=[]
for letter in word.lower():
if letter in vowels:
if letter not in Stack:
Stack.append(letter)
print(Stack)
print('The total number of unique vowels present in',word,'are',len(Stack))

3. Julie has created a dictionary containing names and marks as key value pairs of
6 students. Write a program, with separate user defined functions to perform the
following operations:
● Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 75.
● Pop and display the content of the stack. For example:
If the sample content of the dictionary is as follows:
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
OM BOB ANU TOM
Code:
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
def PUSH(S,N):
S.append(N)

def POP(S):
if S!=[]:
return S.pop()
else:
return None

ST=[]
for k in R:
if R[k]>=75:
PUSH(ST,k)

while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break

4. Alam has a list containing 10 integers. You need to help him create a program
with separate user defined functions to perform the following operations based on
this list.
● Traverse the content of the list and push the even numbers into a stack.
● Pop and display the content of the stack. For Example:
If the sample Content of the list is as follows:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]

Sample Output of the code should be:


38 22 98 56 34 12
Code:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
def PUSH(S,N):
S.append(N)

def POP(S):
if S!=[]:
return S.pop()
else:
return None

ST=[]
for k in N:
if k%7==0:
PUSH(ST,k)

while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
5. 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.

st=[]
def PUSH(Arr):
for i in Arr:
if i%5==0:
st.append(i)
if len(st)==0:
print("Stack is Empty")
else:
for i in range(len(st)-1,1,-1):
print(st[i])
6. Write a function in Python, Addnew(Book) and Remove(Book), to add a new
book and remove a book from a list of books, considering them to act as PUSH and
POP operations of the data structure Stack.

Code:
Book=[]
def Addnew(Book):
Bookname=input(‘Enter book name’)
Book.append(Bookname)

def Remove(Book):
if Book==[]:
print(‘Stack Underflow/ No Book Available’)
else:
print(‘Deleted book is:’,Book.pop())

7. Write a function in Python, MakePush(Package), MakePop(Package) to add a


new package and delete a package from a list of Package description, considering
them to act as PUSH and POP operations of the data structure Stack.

Code:
Package=[]
def MakePush(Package):
Packagename=input(‘Enter package name’)
Package.append(Packagename)

def MakePop(Package):
if Package==[]:
print(‘Stack Underflow/No Package Available’)
else:
print(‘Delted package is:’,Package.pop())

8. A list contains following record of a customer:


[Customer_name, Phone_number, City]
Write the following user defined functions to perform given operations on the stack
named status:
(i) Push_element() - To Push an object containing name and Phone number of
customers who live in Goa to the stack
(ii) Pop_element() - To Pop the objects from the stack and display them. Also,
display “Stack Empty” when there are no elements in the stack.

For example:
If the lists of customer details are:
[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777”,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”]
The stack should contain
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]

The output should be:


[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]
Stack Empty

Code:
status=[]
def Push_element(cust):
if cust[2]=="Goa":
L1=[cust[0],cust[1]]
status.append(L1)

def Pop_element ():


for i in status:
if status!=[]:
print(status.pop())
else:
print('Empty')

def Pop_element ():


num=len(status)
while len(status)!=0:
dele=status.pop()
print(dele)
num=num-1
else:
print("Stack Empty")

** Any one Pop_element() function you can use.

9. Write a function in Python, Push(SItem) where , SItem is a dictionary containing


the details of stationary items– {Sname:price}.
The function should push the names of those items in the stack who have price
greater than 75. Also display the count of elements pushed into the stack.

For example:
If the dictionary contains the following data:
Ditem={"Pen":106,"Pencil":59,"Notebook":80,"Eraser":25}

The stack should contain


Notebook
Pen

The output should be:


The count of elements in the stack is 2

Code:
stackItem=[]
def Push(SItem):
count=0
for k in SItem:
if (SItem[k]>=75):
stackItem.append(k)
count=count+1
print("The count of elements in the stack is : ", count)

10.
Code:

Only3_5=[]
def Push3_5(N):
for i in N:
if i%3==0 or i%5==0:
Only3_5.append(i)

Num=[]
i=1
while i<=5:
n=int(input('Enter a number'))
Num.append(n)
i+=1

Push3_5(Num)
while len(Only3_5)!=0:
print(Only3_5.pop(),end=' ')
else:
print("stack is Empty")

You might also like