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

Data Structure - Stack-1

A stack is a linear data structure that follows LIFO (Last In First Out) principle, allowing elements to be inserted and removed from only one end called the top; it can be implemented using a list in Python with push and pop operations to add and remove elements from the top of the stack; key operations on a stack include push to insert, pop to remove, and peek to access without removing the top element.

Uploaded by

Movie ghar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Data Structure - Stack-1

A stack is a linear data structure that follows LIFO (Last In First Out) principle, allowing elements to be inserted and removed from only one end called the top; it can be implemented using a list in Python with push and pop operations to add and remove elements from the top of the stack; key operations on a stack include push to insert, pop to remove, and peek to access without removing the top element.

Uploaded by

Movie ghar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Data Structure

Stack
What is Data structure
A data structure defines a mechanism to store, organize and access
data along with operations (processing), that can be efficiently
performed on the data.
A data structure
● is a named group of data of different data type
● which is stored in a specific way
● and can be processed as a single unit
● Every data structure has well defined operations, behavior and
properties
Data type vs. Data structure
DATA TYPE defines
● the type of values that can be stored and
● the operations which can be performed.
For example in int data type only numbers without decimal values can be
represented
DATA STRUCTURE is a physical implementation of data in memory
● that clearly defines a way of storing, accessing and manipulating of data
stored in data structures.
● Every data structure has a specific way of insertion and deletion
For example STACK works on a LIFO principle i.e. all operations take place
from one end i.e. TOP of the STACK whereas a QUEUE works on a FIFO
principle i.e. item inserted first will be deleted (removed) first from the
QUEUE.
Types of Data Structures

DATA STRUCTURES

SIMPLE COMPOUND

Integer Float string Boolean LINEAR NON-LINEAR

Stack
Tree
Queue
Graph

Linked List
Types of Data structures

DATA STRUCTURES can be classified into two types:


● SIMPLE DATA STRUCTURES: these are built in from the primitive
data types like integer, float and boolean.
● COMPOUND DATA STRUCTURES: Simple data structure can be
combined in various ways to form more complex structure called
compound Data structure.
Compound Data Structure can be classified into:
● Linear Data Structure - single level data structure.
● Non Linear Data Structure - multi level data structure
Linear vs. Non Linear Data Structure
Linear Data Structure
● A Data structure is said to be linear if the elements form a
sequence and can be accessed one after the other i.e the
elements are attached to its previous and next adjacent.
● Examples of Python built in Linear data structures are List,
string, tuple and some user defined Linear Data structure
are stack, queue and Linked list.
Nonlinear Data Structure
● A Data structure is said to be nonlinear if the data elements
are attached in hierarchical manner and because of which
elements can’t be traversed in a single run only.
● Examples are Trees, Graphs etc. 6
Python Data Structures
DATA STRUCTURES

PRIMITIVE NON PRIMITIVE

Integer Float String Boolean BUILT-IN USER-DEFINED

List Stack

Tuple Queue

Set Tree

Dictionary Graph
Primitive and Non Primitive data structures
Primitive data structures is the basic way of representing data,
which contain simple values.
Examples of Primitive data types are integer, float, Boolean and
String.
Non Primitive data structures are advanced and a complex way
of representing data that contain a collection of values in various
formats.
Non Primitive Data types are derived from the primitive data and
offer increased functionality.
Non Primitive data structures can be further classified into built-in
and user defined.
Non Primitive data structures
Built-in Data Structure
● Python has implicit support for Built in Data Structures, which
include List, Dictionary, Tuple and Set.
● These structures are designed to organize multiple elements in a
way so that certain operations on each element as well as the
collective data unit could be performed easily.
● For example, list is a sequence data structure in which each
element may be of different types. Different operations like
reversal, slicing, counting of characters can be performed on them.
User defined data structure
User Defined Data structures are not supported by Python but can be
programmed to reflect the same functionality using concepts supported
by python.
Stack
● A stack is a Linear data structure
● Implemented using LIFO principle (Last in First out)
● Insertion and deletion can take place from one end called the TOP of the
stack
● Last element which entered the stack is the first one to be removed from the
stack
● Real life examples - pile of plates, pile of books, bangles worn on a wrist etc.
● Computer based examples
● UNDO operations in applications,
● function calls in programming,
● when user browses the internet for information retrieval, the URLs are
places on the stack ie. the current page accessed by the user is kept on the
top and the previous pages are kept at the bottom. Thus when the user
clicks on the BACK button, it moves in the reverse order through the pages.
Operations on a Stack
Two fundamental operations are possible on a stack, namely PUSH and POP.
● Push operation refers to the Insertion operation in a stack. Push operation
adds a new element at the TOP of the stack.
● Elements can be added onto the stack till the stack is FULL.
● Trying to add an element into a stack which is already full results in an
exception called “OVERFLOW”. Overflow occurs when there is no memory
left to accommodate the new item.
In python overflow condition usually does not occur since stack is
represented as list in which unlimited elements can be stored.
● POP refers to the process of removing the TOP most element from the stack.
● An element can be removed until the stack is not EMPTY.
● Any attempt to remove an element from an empty stack iwill result in an
exception known as “UNDERFLOW”.
Operations on a Stack
PUSH POP
12 12
12
37 37 37
99 99 99

STACK

Peek is an additional operation, which can be used on Stack.


Peek operation refers to accessing the value at the stack’s top without
removing it. It is also referred as Inspection.
Implementation of Stack
● Since stack is a linear and an ordered collection of items, the simple way to
implement a stack is using the data type list.
● A stack implemented as a list inherits all properties of a list.
● However, insertion and deletion in a list-implemented stack can occur at the top
only.

Basic operations on a Stack are:


1. Creating a stack
2. Adding elements on a Stack (PUSH operation)
3. Checking for an empty stack
4. Deleting elements from a Stack (POP operation)
5. Displaying all the elements of a Stack (peek operation/Traversal)
Stack Operation – Creation Of Stack
● In Python programming stack is implemented as a list.
● A empty list to be implemented as stack can be created either by using
- Python’s in built method list() or
- by assigning the object to an empty list
Syntax : Stack = list() # Empty stack created using list()
OR
Stack = [] # Empty stack assigned to empty list
▪ Here, Stack is an object of list type and does not contain any elements.
▪ In order to access the elements of the list object Stack, index values are
used i.e the first element in the Stack will be Stack[0], the second will be at
Stack[1], and so on.
● For every stack, an integer object Top is created, which stores the index of the
last inserted element. When the empty stack is created, the object Top is
initialized to None indicating that stack is empty (Underflow condition)
Stack Operation – PUSH (Adding new elements)
A new element can be added into the Stack using the Python built in method,
append().

Syntax : ListObject.append(element)

Stack = list() # empty stack created


top = None #top = None indicates empty stack
num = int(input("Enter element to push – "))
Stack.append(num) # Element pushed into the stack
if top == None:
top = 0
else:
top = top + 1
Stack Operation - Check for Empty Stack
The operations like deleting an element from a Stack or displaying all the elements,
it has to be ensured that, Stack is not empty. Otherwise, it will result in an
Underflow exception.
Alternative Methods to check empty stack -
i. Initially when the stack is created as empty list, the object top is assigned to
None. So to check whether the stack is empty or not, top is compared to
None.
If the stack is empty then the top is equal to None otherwise it stores the
integer index value of the last inserted element.
if top == None:
print("Stack is empty - Underflow")
ii. To check for empty stack, the list object Stack can be compared with []

if Stack == []:
print("Stack is empty - Underflow")
Stack Operation - Check for Empty Stack
iii. The len() function can be used on the list object stack and if it returns 0,
then stack is empty

if len(Stack) == 0: # if not len(Stack):


print("Stack is empty - Underflow")

iv. The underflow condition of the List object Stack can also be checked by
using the not operator .
if not stack:
print("Stack is empty - Underflow")
Stack Operation - POP operation
● The list method pop() is used to remove element from the list object stack.
Syntax : object = List_object.pop()
● The pop() method removes the last value from the list object and returns it.
● When pop operation is performed on a stack with 1 element, after deleting the
element the stack will be empty. Hence, in that situation the top should be
initialized to None (Stack underflow condition)
if top == None: #or Stack == [] or len(Stack) == 0
print("Underflow - stack is empty")
else:
if len(Stack) == 1: #Stack will not exist after deletion
top = None #Stack not existing case
else:
top -= 1
print("Deleted element - ", Stack.pop())
Stack Operation – Traversal / Inspection
• Traversal refers to moving through the elements of the stack.
• In traversal process, the element in the top position (the last inserted
element) get displayed first and elements are processed in reverse order
using a looping statement (i.e the last inserted element will be displayed
first).
• Before traversing a linked stack, it is required to check the stack for
underflow situation

if top == None:
print("Underflow , stack is empty") #Alternative Method -
else: if stack = []:
for i in range(top,-1,-1): print("Underflow , stack is empty")
print(Stack[i]) else:
size = len(stack) - 1
for i in range(size,-1,-1):
print(Stack[i])
Stack Operation
Write a menu driven program to implement a stack where each element is an integer. The
program should have the following options. Write UDF for each option-
i. Push ii. Pop iii. Display all iv. Display all even elements

def push(Stack,num):
global top def pop(Stack):
if top == None: global top
top = 0 #One element in Stack if top == None:
else: print("stack underflow")
top = top+1 else:
Stack.append(num) if len(Stack) == 1: # 1 element in stack
print(Stack) top = None
else:
top = top -1
num = Stack.pop()
print("Deleted element - ",num)
Stack Operation
Write a menu driven program to implement a stack where each element is an integer. The
program should have the following options. Write UDF for each option-
i. Push ii. Pop iii. Display all iv. Display all even elements

def disp(Stack):
if top == None:
print("stack underflow") def dispeven(Stack):
else: cnt = 0
for i in range(top,-1,-1): if top == None:
print(Stack[i]) print("stack underflow")
else:
for i in range(top,-1,-1):
if Stack[i] %2 == 0:
print(Stack[i],end=' ')
cnt+=1
print("No of even elements - ",cnt)
Stack Operation
Write a menu driven program to implement a stack where each element is an integer. The
program should have the following options. Write UDF for each option-
i. Push ii. Pop iii. Display all iv. Display all even elements
Stack = []
top = None
while True:
print("1:push\n2:pop\n3: traverse\n4:\
Count & display even values”)
ch = int(input("Enter choice")) elif ch == 3:
if ch == 1: disp(Stack)
n =int(input("Enter element")) elif ch == 4:
push(Stack,n) dispeven(Stack)
elif ch == 2: ans = input("Want to continue y/n")
print("Deleted – ",pop(Stack)) if ans in "Nn":
break
Stack Operation
Write a program to create a stack containing employee data, consisting of
Empcode, Empname and Salary. Include functions to:
1. Push() - push the employee record into the stack
2. Pop() - pop the employee record from the stack
3. isempty() - check whether the stack is empty or not
4. dispstack() - display all the employee records of the stack
5. Display all employee records earning salary > user given salary

def isempty(stack):
if len(Empstack) == 0:
return True
else:
return False
Stack Operation
Write a program to create a stack containing employee data, consisting of
Empcode, Empname and Salary. Include functions to:
1. Push() - push the employee record into the stack
2. Pop() - pop the employee record from the stack
3. isempty() - check whether the stack is empty or not
4. dispstack() - display all the employee records of the stack
5. Display all employee records earning salary > user given salary
def pop(Empstack):
global top def push(Empstack,newemp):
if isempty(Empstack): global top
return("stack underflow") if isempty(Empstack): #Stack not existing
else: top = 0
if len(Empstack) == 1: else:
top = None top = top+1
else: Empstack.append(newemp)
top = top-1 print("Stack - ",Empstack)
return Empstack.pop()
Stack Operation
Write a program to create a stack containing employee data with Empcode, Empname
and Salary represented as a list, . Include functions to:
1. Push() - push the employee record into the stack
2. Pop() - pop the employee record from the stack
3. isempty() - check whether the stack is empty or not
4. dispstack() - display all the employee records of the stack
5. Display all employee records earning salary > user given salary
def dispsal(Empstack,sal):
def disp(Empstack): ctr = 0
if isempty(Empstack): #Stack not existing
if isempty(Empstack): #Stack underflow
return ("stack underflow")
print("Stack Underflow") else:
else: for i in range(top,-1,-1):
for i in range(top,-1,-1): if Empstack[i][2] > sal:
print(Empstack[i])
print(Empstack[i],end=' ')
ctr += 1
return ctr
Stack Operation
Write a program to create a stack containing employee data, with Empcode, Empname and
Salary. Include functions to:
1. Push() - push the employee record into the stack
2. Pop() - pop the employee record from the stack
3. isempty() - check whether the stack is empty or not
4. dispstack() - display all the employee records of the stack
5. Display all employee records earning salary > user given salary
Empstack,top = [], None
while True:
print("1:push \n2:pop \n3:traverse \n4:disp for sal>user given salary \n")
ch = int (input("Enter choice (1-4) - "))
if ch == 1:
emp = [] #Stack as empty list
empno,name = int(input("Enter empno -")), input("Enter name - ")
salary = float(input("Enter salary - "))
emp = [empno,name,salary]
push(Empstack,emp)
Stack Operation
Write a program to create a stack containing employee data, with Empcode, Empname and
Salary. Include functions to:
1. Push() - push the employee record into the stack
2. Pop() - pop the employee record from the stack
3. isempty() - check whether the stack is empty or not
4. dispstack() - display all the employee records of the stack
5. Display all employee records earning salary > user given salary
elif ch == 4:
elif ch == 2: sal = float(input("Enter salary to -"))
res = pop(Empstack) res = dispsal(Empstack,sal)
if res == "stack underflow": if res == "stack underflow":
print("stack empty") print("stack underflow")
else:
else:
print("\nNo. of employees \
print("deleted element - ",res)
earning > ",sal, " = ",res)
elif ch == 3: ans = input("Want to continue y/n")
disp(Empstack) if ans in "Nn":
break
Stack Operation
Write a program to create a stack containing student data, consisting of
Admissionno, Name and Percentage represented as a list. Include functions to:
1. Push() - push the student record into the stack
2. Pop() - pop the student record from the stack
3. isempty() - check whether the stack is empty or not
4. dispstack() - display all the student records of the stack
5. Display all student records scoring percentage = user given percentage

def push(studstack,newstud):
global top
def isempty(stack): if isempty(studstack): #Stack not existing
if len(studstack) == 0: top = 0
return True else:
else: top = top+1
return False studstack.append(newstud)
print("Stack - ",studstack)
Stack Operation
Write a program to create a stack containing student data, consisting of
Admissionno, Name and Percentage. Include functions to:
1. Push() - push the student record into the stack
2. Pop() - pop the student record from the stack
3. isempty() - check whether the stack is empty or not
4. dispstack() - display all the student records of the stack
5. Display all student records earning percentage = user given percentage
def pop(studstack):
global top
if isempty(studstack):
return("stack underflow")
else:
if len(studstack) == 1:
top = None
else:
top = top-1
return studstack.pop()
Stack Operation
Write a program to create a stack containing student data, consisting of
Admissionno, Name and Percentage. Include functions to:
1. Push() - push the student record into the stack
2. Pop() - pop the student record from the stack
3. isempty() - check whether the stack is empty or not
4. dispstack() - display all the student records of the stack
5. Display all student records earning percentage = user given percentage
def dispperc(studstack,per):
def disp(studstack): ctr = 0
if isempty(studstack): #Stack underflow
if isempty(studstack): #Stack not existing
return ("stack underflow")
print("Stack Underflow")
else:
else: for i in range(top,-1,-1):
for i in range(top,-1,-1): if studstack[i][2] == per:
print(studstack[i]) print(studstack[i],end=' ')
ctr += 1
return ctr
Stack Operation
Write a program to create a stack containing student data, consisting of
Admissionno, Name and Percentage. Include functions to:
1. Push() - push the student record into the stack
2. Pop() - pop the student record from the stack
3. isempty() - check whether the stack is empty or not
4. dispstack() - display all the student records of the stack
5. Display all student records earning percentage = user given percentage
studstack,top = [], None
while True:
print("1:push \n2:pop \n3:traverse \n4:disp for perc = user given perc \n")
ch = int (input("Enter choice (1-4) - "))
if ch == 1:
stud = [] #Stack as empty list
admno,name = int(input("Enter admno -")), input("Enter name - ")
perc = float(input("Enter percentage - "))
stud= [admno,name,perc]
push(studstack,stud)
Stack Operation
Write a program to create a stack containing student data, consisting of
Admissionno, Name and Percentage. Include functions to:
1. Push() - push the student record into the stack
2. Pop() - pop the student record from the stack
3. isempty() - check whether the stack is empty or not
4. dispstack() - display all the student records of the stack
5. Display all student records earning percentage = user given percentage
elif ch == 4:
elif ch == 2: per = float(input("Enter percentage-"))
res = pop(studstack) res = dispperc(studstack,per)
if res == "stack underflow": if res == "stack underflow":
print("stack empty") print("stack underflow")
else: else:
print("deleted element - ",res) print("\nNo. of students with \
perc = ",per, " = ",res)
elif ch == 3:
ans = input("Want to continue y/n")
disp(studstack)
if ans in "Nn":
break
Stack Operation
Write a program to create a stack containing item details, consisting of
Item no, item Name and Price represented as a list of dictionaries where the details
of each item is represented as a dictionary with item no as key and item name and
price as value. Include functions to:
1. Push() - push the item record into the stack
2. Pop() - pop the item record from the stack
3. isempty() - check whether the stack is empty or not
4. dispstack() - display all the item records of the stack
5. Display all item records having price> user given price
def push(itstack,item):
global top
itstack.append(item)
if top== None:
top=0
else:
top=top+1
print("Stack - ",itstack)
Stack Operation
def pop(itstack):
global top
if top==None:
return("stack underflow") def disp(itstack):
else: if top==None:
if len(itstack)== 1: print("Stack empty..Underflow")
top=None else:
print("Stack under flow") for i in range(top,-1,-1):
else: print(itstack[i])
top=top-1
delitem = itstack.pop()
return delitem
Stack Operation
def disppr(itstack,sprice): itstack = list()
ctr = 0 top = None
if top==None: while True:
return ("stack underflow") print("1:push\n2:pop\n3:traverse\n\
else: 4:Count\ for price > user given price\n")
for it in itstack: ch =int (input("Enter choice (1-4) - "))
itrec= list(it) if ch==1:
ino = itrec[0] item = {}
if it[ino][1]> sprice: ino = int(input("Enter Itemno -"))
ctr+=1 name = input("Enter Item name - ")
return ctr price = float(input("Enter Price - "))
item[ino] =[name,price]
push(itstack,item)
Stack Operation
elif ch==2:
res = pop(itstack)
if res =="stack underflow":
print("stack empty")
else: elif ch==4:
print("deleted element - ",res) p = float(input("Enter Price to search-"))
elif ch==3: res = disppr(itstack,p)
disp(itstack) if res == "stack underflow":
print("stack underflow")
else:
print("\nNo. of items with price > ",p,\
" = ",res)
ans=input("Want to continue y/n")
if ans in "Nn":
break
Stack Operation
John has created a dictionary containing names and salary as key value pairs
of 6 employees. Perform the following operations to get the desired output as
shown in Sample Output
● Push the keys (name of the employee) of the dictionary into a stack, where
the corresponding salary is greater than 7500
● Pop and display the content of the stack
Make separate user defined functions to perform Stack PUSH and Stack POP
functions for each element.
For example:
If the sample content of the dictionary is as follows:
R = {"OM":7600, "JAI":4500, "BOB":8900, "ALI":6500, "ANU":9000,
"TOM":8200}
The output from the should be: TOM ANU BOB OM
Stack Operation
def PUSH(S,N):
global top R = {}
S.append(N) while True:
if top== None: nm = input("enter name –")
top=0 R[nm] = float(input("Enter salary –"))
else:
top = None
top=top+1
ST = []
def POP(S): for k in R:
global top if R[k]>=7500:
if top==None: PUSH(ST,k)
return("stack underflow") while True:
elif len(itstack)== 1: if ST != []:
top=None print(POP(ST),end=" ")
print("Stack under flow") ans = input(“want to pop another")
else: if ans == "Nn“:
top=top-1 break
delemp = s.pop()
return delemp
Stack Operation
Write a program to create a stackA with each element as an integer . Write a menu driven
programs to include functions to:
1. Push() - push the integer element into the stackA
2. Pop() - pop the integer element from the stackA
3. isempty() - check whether the stackA is empty or not
4. dispstack() - display stack contents
5. Transfer all perfect numbers from stackA to StackB and Display
6. Transfer all palindrome numbers from stackA to StackB and Display
7. Transfer all prime numbers from stackA to StackB and Display
def push(stackA,num):
def stackEmpty(stackA): global top
if len(stackA) == 0: stackA.append(num)
return True if stackEmpty(stackA):
else: top=0
return False else:
top +=1
print(stackA)
Stack Operation
def pop(stackA):
global top
if stackEmpty(stackA):
return "Stack empty"
else:
if len(stackA)== 1: def disp(stack,topn):
top=None if stackEmpty(stack):
else:
print("Stack underflow")
top-=1
return stackA.pop() else:
for i in range(topn,-1,-1):
print(stack[i])
Stack Operation
def checkperfect(stackA):
stackB, topB = [], None
if stackEmpty(stackA): def checkpalin(stackA):
print("Stack underflow") stackB,topB = [], None
else: if stackEmpty(stackA):
for i in range(top,-1,-1): print("Stack underflow")
num=stackA[i] else:
sum=0 for i in range(top,-1,-1):
for j in range(1,num): num = stackA[i]
if num%j==0: string = str(num)
sum+=j if string == string[::-1]:
if sum==num: stackB.append(num)
stackB.append(num) if topB==None:
if topB==None: topB=0
topB=0 else:
else: topB+=1
topB+=1 disp(stackB,topB)
disp(stackB,topB)
Stack Operation
def checkprime(stackA): stackA,top=[],None
stackB,topB=[],None while True:
if stackEmpty(stackA): print("1:push element in stackA
print("Stack underflow") \n2:pop element from stackA\
else: \n3:display element in stackA\
for i in range(top,-1,-1): \n4:check for perfect\
num=stackA[i] \n5:check for palindromes\
for j in range(2,num//2+1): \n6:check for prime")
if num%j==0: ch=int(input("Enter choice"))
break if ch==1:
else: n=int(input("Enter element"))
stackB.append(num) push(stackA,n)
if topB==None:
topB=0
else:
topB+=1
disp(stackB,topB)
Stack Operation
elif ch==2:
num=pop(stackA)
if num=="Stack empty":
print("Stack is empty")
else:
print("deleted element:",num)
elif ch==3:
disp(stackA,top)
elif ch==4:
checkperfect(stackA)
elif ch==5:
checkpalin(stackA)
elif ch==6:
checkprime(stackA)
ans=input("Want to continue y/n")
if ans in "nN":
break

You might also like