Data Structure
Data Structure
Data type is one of the forms of a variable to which the value can be assigned of a given type
only.
Data structure:
It is a collection of data of different data types.
It is a named group of data of different data types which is stored in a specific way
and can be processed as a single unit.
It has well defined operations , behavior and properties.
Data Type is the kind or form of a variable Data Structure is the collection of different
which is being used throughout the program. It kinds of data. That entire data can be
defines that the particular variable will assign represented using an object and can be
the values of the given data type only used throughout the entire program.
Compound Data Structures : Simple data structures can be combined in various ways to
form mores complex structures called compound data structures. Compound data structures are
classified as :
(a) Linear Data Structure: Data structure in which data elements are arranged sequentially or
linearly, where each element is attached to its previous and next adjacent elements, is called a
linear data structure.
Examples of linear data structures stack, queue, linked list, etc.
(b)Non-linear Data Structure: Data structures where data elements are not placed
sequentially or linearly are called non-linear data structures. These are multilevel
data structures. In a non-linear data structure, we can’t traverse all the elements in a
single run only.
Examples of non-linear data structures are trees and graphs.
Need Of Data Structure :
Features of Stack:
A stack has the following features:
Stack is a simple linear structure that provides only one end for entry and exit of
data(i.e., top of the stack)
No element can be accessed from the middle
It works on LIFO principle. The element entering last into the stack will be deleted first
from it.
The removal of element from a stack is called POP operation.
The insertion of elements in a stack is called PUSH operation
Examples
Advantage of Static data structure :
Fast access time: Static data structures offer fast access time because memory is allocated
at compile-time and the size is fixed, which makes accessing elements a simple indexing
operation.
Predictable memory usage: Since the memory allocation is fixed at compile-time, the
programmer can precisely predict how much memory will be used by the program, which
is an important factor in memory-constrained environments.
Ease of implementation and optimization: Static data structures may be easier to
implement and optimize since the structure and size are fixed, and algorithms can be
optimized for the specific data structure, which reduces cache misses and can increase the
overall performance of the program.
Efficient memory management: Static data structures allow for efficient memory
allocation and management. Since the size of the data structure is fixed at compile-time,
memory can be allocated and released efficiently, without the need for frequent
reallocations or memory copies.
Simplified code: Since static data structures have a fixed size, they can simplify code by
removing the need for dynamic memory allocation and associated error checking.
Reduced overhead: Static data structures typically have lower overhead than dynamic
data structures, since they do not require extra bookkeeping to manage memory allocation
and deallocation.
Advantage Of Dynamic Data Structure :
Flexibility: Dynamic data structures can grow or shrink at runtime as needed, allowing
them to adapt to changing data requirements. This flexibility makes them well-suited for
situations where the size of the data is not known in advance or is likely to change over
time.
Reduced memory waste: Since dynamic data structures can resize themselves, they can
help reduce memory waste. For example, if a dynamic array needs to grow, it can allocate
additional memory on the heap rather than reserving a large fixed amount of memory that
might not be used.
Improved performance for some operations: Dynamic data structures can be more
efficient than static data structures for certain operations. For example, inserting or
deleting elements in the middle of a dynamic list can be faster than with a static array,
since the remaining elements can be shifted over more efficiently.
Simplified code: Dynamic data structures can simplify code by removing the need for
manual memory management. Dynamic data structures can also reduce the complexity of
code for data structures that need to be resized frequently.
Scalability: Dynamic data structures can be more scalable than static data structures, as
they can adapt to changing data requirements as the data grows.
Static Data Structures Dynamic Data Structures
Have a fixed size Can change size during runtime
Memory is allocated at the time of Memory is allocated and de allocated as
the creation needed
Access time is constant Access time may vary
More efficient in terms of memory usage Less efficient in terms of memory
usage
Examples: arrays, fixed-size lists etc. Examples: linked lists, stacks, queues etc.
Program-1:
# Stack : Implemented as a List of integers
def isEmpty(stk):
if stk==[ ]:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack is Empty")
else:
top=len(stk)-1 print("\
t",stk[top],"<------top")
for a in range(top-1, -1, -1):
print("\t",stk[a])
#====Main ===
Stack=[]
top=None
while True:
print("\nSTACK 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 the item
Push(Stack,item)
elif ch==2:
Display(Stack)
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")
Program-2:
# Stack : Write a program to implement a stack for these book details(BNO,
BNAME & PRICE
def isEmpty(stk):
if stk==[ ]:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack is Empty")
else:
top=len(stk)-1 print("\
t",stk[top],"<------top")
for a in range(top-1, -1, -1):
print("\t",stk[a])
#====Main ===
Stack=[]
top=None
while True:
print("\nSTACK 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:
BNO=int(input( “Enter book
number :”)
BNAME=input(“ Enter Book
Name :”)
PRICE=float(input(“ Enter price of the
book”)
item=[BNO,BNAME,PRICE]
Push(Stack,item)
elif ch==2:
Display
(Stack)
item=Po
p(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")
***********************************************************************
Applications of Stack:
1.Reversing a Word /Line
In programming, the function call stack is an essential tool for managing function calls.
When a function is invoked, its execution context is pushed onto the stack, including local
variables and the return address. As the function completes, its stack frame is popped,
allowing the program to resume execution in the calling function.
In mathematics and programming, stacks are used for precise expression evaluation,
including the application of stacks in data structure. When evaluating mathematical
expressions, a stack can be employed to keep track of operators and operands, ensuring
the correct order of operations. The LIFO property of stacks helps manage operator
precedence, allowing for the accurate calculation of complex expressions. It simplifies the
process of converting infix expressions to postfix notation for evaluation.
5. Backtracking Algorithms:
Backtracking is a form of recursion which involves choosing only one option out of the
possibilities. Backtracking is used in a large number of puzzle like Sudoku and in
optimization problems such as knapsack.
6. Browser History:
Web browsers utilize stacks to manage users' browsing history efficiently, demonstrating the
application of stack and queue in data structure. Every time a user visits a new web page,
the current page is pushed onto the forward stack, while the previous page is pushed onto
the back stack. This approach enables users to navigate backwards and forward through
their browsing history using the browser's "Back" and "Forward" buttons, providing a
seamless and intuitive web browsing experience.
7. Memory Management:
In programming languages like C and C++, the stack plays a critical role in memory
management, illustrating the application of stack ADT in data structure. It is used to store
function call information, local variables, and execution-related data. The stack segment of a
program's memory is typically allocated for this purpose. As functions are called and return,
memory is efficiently allocated and deallocated from the stack, ensuring effective memory
management and resource optimisation in software development, particularly in low-level
programming.
***