Data Structure: STACK
Data structure: A data structure is a group of data which can be processed as a single unit. This group
of data may be of similar or dissimilar data types. Data Structures are very useful while programming
because they allow processing of the entire group of data as a single unit. This makes managing of
data simpler.
Different Data Structures: The data structures can be classified into following two types:
1. Simple Data Structures: Simple data structures are normally built from primitive data types.
Ex-Linear List.
2. Compound Data Structures: Simple data structure can be combined in various ways to form
compound data structure. It can be classified into two types:
Linear Data Structure: These are single level data structures, whose elements form a
sequence. Ex- Stack, Queue, Linked List.
Non-Linear Data Structure: These are multilevel data structures. Ex- Tree.
DATA STRUCTURES
Simple Data Compound
Structures Data Structures
Linear List Linear Non-Linear
Stack Queue Linked Tree
BY: FARAH ARIF 1
Linear Lists Array: A Linear list or an array refers to a named list of a finite number 'n' of similar data
elements.
Stacks: Stacks are "LIFO" (Last In First Out) lists where insertions and deletions take place only at one
end.
Queues: Queues are "FIFO" (First In First Out) lists where insertions take place at rear end and
deletions take place at the front end.
Linked Lists: A linked-list is a sequence of data structures which are connected together via links.
Linked List is a sequence of links which contains items. Each link contains a connection to another
link.
BY: FARAH ARIF 2
Trees: A tree is non-linear and a hierarchical data structure consisting of a collection of nodes such
that each node of the tree stores a value, a list of references to nodes (the “children”).
Operations on Data Structures: Basic operations are:
1. Insertion: Insertion mean addition of a new data element in a data structure.
2. Deletion: Deletion mean removal of a data element from a data structure.
3. Searching: Searching mean finding for the specific element in a data structure.
4. Traversal: Traversal of a data structure means processing all the data elements of it, one by
one.
5. Sorting: Sorting mean arranging data elements of a data structure in a specified order.
6. Merging: Merging mean combining elements of two similar data structures to form a new data
structure of same type.
Searching in a Linear List: There are many searching algorithms. We shall be discussing two of them
Linear Search and Binary Search.
1. Linear Search: In linear search, the search element is compared with each element of the list,
starting from the beginning of the list. This continues till either the element has been found or
you have reached to the end of the list. That is why this type of searching technique is also called
sequential search.
BY: FARAH ARIF 3
print("------------------------------------Linear Search----------------------------------")
list=eval(input("Enter list elements : "))
item=int(input("Enter a number to search for: "))
length=len(list)
temp=0
for i in range(length):
if list[i]==item:
temp=1
print("Item found at index ",i)
break
if temp==0:
print("Item Not found")
OUTPUT:
-----------------------------Linear Search----------------------------
Enter list elements : [5,4,7,8,6,2,1,0,3,2,4,5,9,8,7]
Enter a number to search for: 3
Item found at index 8
Note: Linear Searching technique is simple to use but has few drawbacks. If the element to
be searched is towards the end of the array, the searching process becomes very time
consuming. This drawback is overcome to a large extent in the next sorting technique i.e.
binary search
2. Binary Search: A binary search is an advanced type of search algorithm that finds and fetches
data from a sorted list of items. It also known as half-interval search.
The binary search works in the following manner:
The search process initiates by locating the middle element of the sorted array of data
After that, the key value is compared with the element
If the key value is smaller than the middle element, then searches analyses the upper
values to the middle element for comparison and matching
In case the key value is greater than the middle element then searches analyses the
lower values to the middle element for comparison and matching.
BY: FARAH ARIF 4
print("----------------------------Binary Search----------------------------")
list=eval(input("Enter list elements : "))
n_list=sorted(list)
print("Sorted Form of Your List :",n_list)
item=int(input("Enter a number to search for: "))
temp=0
start=0
end=len(n_list)-1
while start<=end:
mid=(start+end)//2
if item > n_list[mid]:
start=mid+1
temp=1
elif item < n_list[mid]:
end=mid-1
temp=1
else:
temp=0
break
if temp==0:
print("Item Found at index ",mid)
else:
print("Item Not Found")
OUTPUT:
----------------------------Binary Search----------------------------
Enter list elements : [5,8,7,2,2,5,9,3,0,4,1,6]
Sorted Form of Your List : [0, 1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9]
Enter a number to search for: 3
Item Found at index 4
2D List: Two-dimensional list in Python is just a list of lists(Nested list), so a two-dimensional list can
be defined as follows:
a=[[0,0],[1,1]]
Creating a 2D List:
row=int(input("Enter number of Rows : "))
col=int(input("Enter number of columns : "))
list=[ ]
for r in range(row):
i=[ ]
for c in range(col):
val=int(input("Enter Value : "))
i.append(val)
list.append(i)
print("Created List is : ",list)
BY: FARAH ARIF 5
OUTPUT:
Enter number of Rows : 3
Enter number of columns : 3
Enter Value : 9
Enter Value : 8
Enter Value : 7
Enter Value : 6
Enter Value : 5
Enter Value : 4
Enter Value : 3
Enter Value : 2
Enter Value : 1
Created List is : [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
Traversing a 2D List:
for r in range(row1):
for c in range(col1):
print(A[r][c],end=" ")
print( )
OUTPUT:
9 8 7
6 5 4
3 2 1
Stacks: 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.
It is type of linear data structure.
It follows LIFO (Last In First Out) property.
Insertion / Deletion in stack can only be done from top.
Insertion in stack is also known as a PUSH operation.
Deletion from stack is also known as POP operation in stack.
BY: FARAH ARIF 6
Other Stack term: There are some other terms related to stack, such as Peek, Overflow and
Underflow.
1. Peek: It refers to inspecting the value at the stack’s top without removing it.
2. Overflow: When a stack, implemented as an array, is full and no new element can be
accommodated, it is called an OVERFLOW.
3. Underflow: When a stack is empty and an element's deletion is tried from the stack, it is
called an UNDERFLOW.
print(“----------------------------------------STACK IMPLEMENTATION--------------------------------”).
def isEmpty(s):
if s==[]: #if len(s)==0
return True
else:
return False
def push(s,v):
s.append(v)
print("Value inserted.....")
def pop(s):
if isEmpty(s):
print("Stack Underflow..........")
else:
print("deleted Value : ",s.pop())
def peek(s):
if isEmpty(s):
print("Stack Empty..........")
else:
print("Top Element : ",s[-1])
def display(s):
print(s)
def rev_display(s):
for i in range(len(s)-1,-1,-1):
print(s[i],end=" ")
BY: FARAH ARIF 7
#-----------------------------------------------MAIN PROGRAM----------------------------------------
stack=[ ]
while True:
print("--------------STACK OPERATIONS---------------")
print("................ 1- PUSH.....................")
print("................ 2- POP......................")
print("................ 3- PEEK.....................")
print("................ 4- DISPLAY..................")
print("................ 5- REV_DISPLAY..................")
print("................ 6- EXIT.....................")
ch=int(input("Enter your choice : "))
if ch==1:
val =int(input("Enter the value which you want to PUSH : "))
push(stack,val)
elif ch==2:
pop(stack)
elif ch==3:
peek(stack)
elif ch==4:
display(stack)
elif ch==5:
rev_display(stack)
elif ch==6:
print("EXIT")
break
else:
print("Invalid Entry.....")
OUTPUT:
---------------------------------------------STACK IMPLEMENTATION-------------------------------------
--------------STACK OPERATIONS---------------
................ 1- PUSH.....................
................ 2- POP......................
................ 3- PEEK.....................
................ 4- DISPLAY..................
................ 5- REV_DISPLAY..................
................ 6- EXIT.....................
Enter your choice : 1
Enter the value which you want to PUSH : 10
Value inserted.....
BY: FARAH ARIF 8
--------------STACK OPERATIONS---------------
................ 1- PUSH.....................
................ 2- POP......................
................ 3- PEEK.....................
................ 4- DISPLAY..................
................ 5- REV_DISPLAY..................
................ 6- EXIT.....................
Enter your choice : 1
Enter the value which you want to PUSH : 20
Value inserted.....
--------------STACK OPERATIONS---------------
................ 1- PUSH.....................
................ 2- POP......................
................ 3- PEEK.....................
................ 4- DISPLAY..................
................ 5- REV_DISPLAY..................
................ 6- EXIT.....................
Enter your choice : 1
Enter the value which you want to PUSH : 30
Value inserted.....
--------------STACK OPERATIONS---------------
................ 1- PUSH.....................
................ 2- POP......................
................ 3- PEEK.....................
................ 4- DISPLAY..................
................ 5- REV_DISPLAY..................
................ 6- EXIT.....................
Enter your choice : 1
Enter the value which you want to PUSH : 40
Value inserted.....
--------------STACK OPERATIONS---------------
................ 1- PUSH.....................
................ 2- POP......................
................ 3- PEEK.....................
................ 4- DISPLAY..................
................ 5- REV_DISPLAY..................
................ 6- EXIT.....................
Enter your choice : 4
[10, 20, 30, 40]
--------------STACK OPERATIONS---------------
................ 1- PUSH.....................
................ 2- POP......................
................ 3- PEEK.....................
................ 4- DISPLAY..................
BY: FARAH ARIF 9
................ 5- REV_DISPLAY..................
................ 6- EXIT.....................
Enter your choice : 2
deleted Value : 40
--------------STACK OPERATIONS---------------
................ 1- PUSH.....................
................ 2- POP......................
................ 3- PEEK.....................
................ 4- DISPLAY..................
................ 5- REV_DISPLAY..................
................ 6- EXIT.....................
Enter your choice : 4
[10, 20, 30]
--------------STACK OPERATIONS---------------
................ 1- PUSH.....................
................ 2- POP......................
................ 3- PEEK.....................
................ 4- DISPLAY..................
................ 5- REV_DISPLAY..................
................ 6- EXIT.....................
Enter your choice : 3
Top Element : 30
--------------STACK OPERATIONS---------------
................ 1- PUSH.....................
................ 2- POP......................
................ 3- PEEK.....................
................ 4- DISPLAY..................
................ 5- REV_DISPLAY..................
................ 6- EXIT.....................
Enter your choice : 5
30 20 10
--------------STACK OPERATIONS---------------
................ 1- PUSH.....................
................ 2- POP......................
................ 3- PEEK.....................
................ 4- DISPLAY..................
................ 5- REV_DISPLAY..................
................ 6- EXIT.....................
Enter your choice : 6
EXIT
BY: FARAH ARIF 10