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

Data Structure

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

Data Structure

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

DATA STRUCTURE II

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 Types Data Structures

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.

Implementation through Data Types is a form Implementation through Data Structures is


of abstract implementation called concrete implementation

Can hold different kind and types of data


Can hold values and not data, so it is data less
within one single object

The data is assigned to the data structure


Values can directly be assigned to the data
object using some set of algorithms and
type variables
operations like push, pop and so on.

Time complexity comes into play when


No problem of time complexity
working with data structures

Examples: int, float, double Examples: stacks, queues, tree


 Simple Data Structures : These data structures are normally built from primitive data
types like integers, real numbers, strings, Boolean .

Example- Array or Linear Lists

 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 :

1. Data structure modification is easy.


2. It requires less time.
3. Save storage memory space.
4. Data representation is easy.
5. Easy access to the large database.
Stack:
 A stack is a linear/ sequence structure or a list of elements in which insertion and
deletion can take place only at one end i.e., Stack’s top.
 It is called LIFO (Last In, First Out) 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

Static Data Structure vs Dynamic Data Structure


 Static data structures, such as arrays, have a fixed size and are allocated at compile-time.
This means that their memory size cannot be changed during program execution. Index-
based access to elements is fast and efficient since the address of the element is known.
 Dynamic data structures, on the other hand, have a variable size and are allocated at run-
time. This means that their memory size can be changed during program execution.
Memory can be dynamically allocated or deallocated during program execution. Due to
this dynamic nature, accessing elements based on index may be slower as it may require
memory allocation and deallocation.
Aspect Static Data Structure Dynamic Data Structure

Memory Memory is allocated at


Memory is allocated at run-time
allocation compile-time

Size is fixed and cannot be


Size Size can be modified during runtime
modified

Memory Memory utilization may be Memory utilization is efficient as memory


utilization inefficient can be reused

Access time is faster as it is Access time may be slower due to indexing


Access
fixed and pointer usage

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

A simple example of Stack application is reversal of a given line. These can be


accomplished by pushing each character on to a stack as it is read. When the line is
finished, characters are popped off the Stack and they will come off in the reverse order.

2. Processing of Function Calls:

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.

3. Undo/Redo Mechanism in Text Editors:

This operation is accomplished by keeping all text changes in a Stack.

4. Evaluation of Arithmetic Expressions ( Polish String):

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.

***

You might also like