0% found this document useful (0 votes)
38 views306 pages

Data Structures and Algorithm-1

The document outlines a course on Data Structures and Algorithms, detailing its structure, teaching and examination schemes, and course outcomes. It covers fundamental concepts including data types, data structures, and algorithms, along with various types of data structures such as arrays, linked lists, stacks, queues, binary trees, and graphs. Additionally, it provides information on course materials, web resources, and the importance of data structures in programming.

Uploaded by

pggg1225
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views306 pages

Data Structures and Algorithm-1

The document outlines a course on Data Structures and Algorithms, detailing its structure, teaching and examination schemes, and course outcomes. It covers fundamental concepts including data types, data structures, and algorithms, along with various types of data structures such as arrays, linked lists, stacks, queues, binary trees, and graphs. Additionally, it provides information on course materials, web resources, and the importance of data structures in programming.

Uploaded by

pggg1225
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 306

DATA STRUCTURES

AND
ALGORITHM
BY – PROF. JAGRUTI DANDGE
BASICS OF THE COURSE
• Course Name – Data Structure and Algorithm
• Course Code – ITOEC0010/
ITMDM5001/ITMDM6001/ ITOE0020
• Schemes -
Teaching Scheme Examination Scheme
Lectures: 3 Hrs/ Week ISE I : 15 Marks
Tutorial : 0 ISE II : 15 Marks
Credits : 3 ISE III: 10 Marks
End Semester Exam : 60 Marks
BASICS OF THE COURSE
• COURSE DESCRIPTION:
• The course covers basics of data structures
and algorithms.
• Topics covered in this course include
abstraction, stack, queues, lists, trees, and
graphs, sorting and complexity of algorithm.
• The course enables the students to design
good efficient solutions to real world
problems.
BASICS OF THE COURSE
• COURSE OUTCOMES :
• CO1 : Describe data structures arrays, stacks
and queues
• CO2 : Interpret linked lists, trees and graphs
• CO3 : Demonstrate best-case, average-case
and the worst-case running times of
algorithms using asymptotic analysis for
various sorting and searching problems
• CO4 : Choose the standard design techniques
of algorithms and their applications
BASICS OF THE COURSE
• TEXT AND REFERENCE BOOKS
• 1. Yedidyah Langsam, Moshe J. Augenstein, Aaron
M.Tenenbaum, “Data Structures using C and C++ “ ,
Pearson Pub.
• 2. G.S. Baluja, “Principles of Data Structures using C
and C++”, Dhanpat Rai & Co.,4th Edition
• 3. Computer Algorithms : Horowitz, Sahani,
Rajsekharan , Galgotia Publications Pvt.Ltd
• 4. Fundamentals of Algorithms: Brassard, Bratley ,
Prentice Hall
BASICS OF THE COURSE
• WEB RESOURCES:
• 1. https://nptel.ac.in/courses/106102064
• 2. https://nptel.ac.in/courses/106106127
• 3.https://www.coursera.org/specializatio
ns/data-structures-algorithms
INTRODUCTION OF THE SUBJECT
• DATA –
• Processed information
• Interrelated information
INTRODUCTION OF THE SUBJECT
• STRUCTURE :
–The way that the parts of something
are put together or organized
–To arrange something in an organized
way
INTRODUCTION OF THE SUBJECT
•DATA STRUCTURE :
• Storage that is used to store and organize
data.
• A way of arranging data on a computer so
that it can be accessed and updated
efficiently.
INTRODUCTION OF THE SUBJECT
• ALGORITHM :
• The word Algorithm means ” A set of finite
rules or instructions to be followed in
calculations or other problem-solving
operations ”
INTRODUCTION OF THE SUBJECT
• Or
” A procedure for solving a mathematical
problem in a finite number of steps that
frequently involves recursive operations”.
INTRODUCTION OF THE SUBJECT
UNIT 1

INTRODUCTION TO DATA
STRUCTURES
UNIT 1
• SYLLABUS :
• Introduction to data structures, Concept of Data
type, Data object, Need of Data Structure, Types
of Data Structure, Linear data structures,
Introduction to Arrays, sorting algorithms with
efficiency, Stacks, static and dynamic
representation of stack, Stack Operations ,
Applications of stack, Queues, static & dynamic
representation of queues, Operations on queues,
Circular queue, priority queues
CONCEPT OF DATA TYPE
• What is Data Type? :
• The term “data type” in software programming
describes the kind of value a variable possesses
and the kinds of mathematical, relational, or
logical operations that can be performed on it
without leading to an error.
• Numerous programming languages, for instance,
utilize the data types string, integer, and floating
point to represent text, whole numbers, and
values with decimal points, respectively.
CONCEPT OF DATA TYPE
• An interpreter or compiler can determine how a
programmer plans to use a given set of data by
looking up its data type.
• The data comes in different forms. Examples
include:
• your name – a string of characters
• your age – usually an integer
• the amount of money in your pocket- usually
decimal type
• today’s date – written in date time format
CONCEPT OF DATA TYPE
CONCEPT OF DATA TYPE
• 1. Primitive Data Types:
• Primitives are predefined data types that are
independent of all other kinds and include basic
values of particular attributes, like text or
numeric values.
• They are the most fundamental type and are
used as the foundation for more complex data
types.
• Most computer languages probably employ some
variation of these simple data types.
CONCEPT OF DATA TYPE
• Common Primitive Data Types in
Programming:
Data Type Definition Examples
represent numeric data type for
Integer (int) 300, 0 , -300
numbers without fractions
Floating Point represent numeric data type for 34.67, 56.99, -
(float) numbers with fractions 78.09

represent single letter,


Character (char) punctuation mark, symbol, or a, !
blank space
CONCEPT OF DATA TYPE
Data Type Definition Examples
true- 1,
Boolean (bool) True or false values
false- 0
Date in the YYYY-MM-DD
Date 2024-01-01
format (ISO 8601 syntax)
Time in the hh:mm:ss format
for the time of day, time
Time 12:34:20
since an event, or time
interval between events
CONCEPT OF DATA TYPE

Data Type Definition Examples

Date and time together in the 2024 -01-01


Datetime
YYYY-MM-DD hh:mm:ss format 12:34:20
CONCEPT OF DATA TYPE
• 2. Composite Data Types:
• Composite data types are made up of various
primitive kinds that are typically supplied by the user.
• They are also referred to as non-primitive data types.
• Composite types fall into four main categories: semi-
structured (stores data as a set of relationships);
multimedia (stores data as images, music, or videos);
homogeneous (needs all values to be of the same
data type); and tabular (stores data in tabular form).
CONCEPT OF DATA TYPE
• Some common composite data types are as
follow:
Data Type Definition Examples
Sequence of characters, digits, or hello , ram , i
String (string)
symbols—always treated as text am a girl
List with a number of elements in
arr[4]= [0 , 1
array a specific order—typically of the
,2,3]
same type
Blocks of memory that are
pointers dynamically allocated are *ptr=9
managed and stored
CONCEPT OF DATA TYPE
• 3. User Defined Data Types:
• A user-defined data type (UDT) is a data type
that derived from an existing data type. You
can use other built-in types already available
and create your own customized data types.
CONCEPT OF DATA TYPE
• Some common user defined data types are as
follow:
Data Type Definition Examples
Small set of predefined unique
Enumerated values (elements or enumerators) Sunday -0,
Type (enum) that can be text-based or Monday -1
numerical
allows to combining of data items
Structure of different kinds
struct s{ …}

contains a group of data objects


Union that can have varied data types
union u {…}
DATA OBJECT
DATA OBJECT
• Definition: A Data object represents a
container for data values, a place where
data values may be stored and later
retrieved.
OR
• Definition: A Location in memory with an
assignment name in the actual computer.
DATA OBJECT
• Data objects can be:
• 1) at program execution- Programmer-defined
-(example variables, constant, arrays, files etc)

• 2) not directly accessible to programmer-


system defined- run time storage, stacks, file
buffers, free space lists.
DATA OBJECT
• Data object is usually represented as
storage in Computer memory and a data
value is represented by a pattern of
bits. So we can represent the relation
between Data Object and Data value.
• For eg –
• A=17;
DATA OBJECT
• Data object : The location in the
Computer’s memory with the name A
• Data Value : A bit pattern used by
translator whenever the no 17 is used in
the program
• Bound Variable : Value 17
DATA OBJECT
• Binding and Attributes of Data Object:
• 1) Type: This associates the data object with the
set of data values that the object may take.
• 2) location: This associate the binding of a
storage location in memory where the data
object is represented. Only storage management
routines can only change add data object in the
virtual computer.
• 3) Value: This binding is usually the result of an
assignment operation.
DATA OBJECT
• 4) Name: The binding to one or more names by
which the object maybe referenced during
program execution is usually set up by
declaration and modified by subprogram calls the
returns.
• 5) Component: The binding of a data object to
one or more data object of which it is a
component is often represented by a pointer
value. And may be modified by a change in
pointer.
NEED OF DATA
STRUCTURE
NEED OF DATA STRUCTURE
• The structure of the data and the synthesis of the
algorithm are relative to each other.
• Data presentation must be easy to understand so the
developer, as well as the user, can make an efficient
implementation of the operation.
• Data structures provide an easy way of organising,
retrieving, managing, and storing data.
• Data structure modification is easy.
• It requires less time.
• Save storage memory space.
• Data representation is easy.
• Easy access to the large database
TYPES OF DATA
STRUCTURE
TYPES OF DATA STRUCTURE
• There are 2 types of Data structure:
• Linear Data Structure
• Non-Linear Data Structure.
• Linear Data Structure:
• Elements are arranged in one dimension ,also
known as linear dimension.
• Example: lists, stack, queue, etc.
TYPES OF DATA STRUCTURE
• Non-Linear Data Structure
• Elements are arranged in one-many, many-
one and many-many dimensions.
• Example: tree, graph, table, etc.
TYPES OF DATA STRUCTURE
TYPES OF DATA STRUCTURE
• 1. ARRAY:
• An array is a collection of data items stored at
contiguous memory locations.
• The idea is to store multiple items of the same
type together.
• This makes it easier to calculate the position of
each element by simply adding an offset to a
base value, i.e., the memory location of the first
element of the array (generally denoted by the
name of the array).
TYPES OF DATA STRUCTURE
TYPES OF DATA STRUCTURE
• 2. LINKED LISTS:
• Like arrays, Linked List is a linear data
structure. Unlike arrays, linked list
elements are not stored at a
contiguous location; the elements
are linked using pointers.
TYPES OF DATA STRUCTURE
TYPES OF DATA STRUCTURE
• 3. STACK:
• Stack is a linear data structure which follows a
particular order in which the operations are
performed.
• The order may be LIFO(Last In First Out) or
FILO(First In Last Out).
• In stack, all insertion and deletion are
permitted at only one end of the list.
TYPES OF DATA STRUCTURE
TYPES OF DATA STRUCTURE
• Stack Operations:
• push(): When this operation is performed, an
element is inserted into the stack.
• pop(): When this operation is performed, an element
is removed from the top of the stack and is returned.
• top(): This operation will return the last inserted
element that is at the top without removing it.
• size(): This operation will return the size of the stack
i.e. the total number of elements present in the
stack.
• isEmpty(): This operation indicates whether the stack
is empty or not.
TYPES OF DATA STRUCTURE
• 4. QUEUE:
• Like Stack, Queue is a linear structure which
follows a particular order in which the
operations are performed.
• The order is First In First Out (FIFO).
• In the queue, items are inserted at one end
and deleted from the other end.
TYPES OF DATA STRUCTURE
• A good example of the queue is any queue of
consumers for a resource where the consumer
that came first is served first.
• The difference between stacks and queues is
in removing. In a stack we remove the item
the most recently added; in a queue, we
remove the item the least recently added.
TYPES OF DATA STRUCTURE
TYPES OF DATA STRUCTURE
• Queue Operations:
• Enqueue(): Adds (or stores) an element to the
end of the queue..
• Dequeue(): Removal of elements from the
queue.
• Peek() or front(): Acquires the data element
available at the front node of the queue without
deleting it.
• rear(): This operation returns the element at the
rear end without removing it.
• isFull(): Validates if the queue is full.
• isNull(): Checks if the queue is empty.
TYPES OF DATA STRUCTURE
• 5. BINARY TREE:
• Unlike Arrays, Linked Lists, Stack and queues,
which are linear data structures, trees are
hierarchical data structures.
• A binary tree is a tree data structure in which
each node has at most two children, which are
referred to as the left child and the right child.
• It is implemented mainly using Links.
TYPES OF DATA STRUCTURE
• A Binary Tree is represented by a pointer to
the topmost node in the tree.
• If the tree is empty, then the value of root is
NULL.
• A Binary Tree node contains the following
parts.
TYPES OF DATA STRUCTURE
TYPES OF DATA STRUCTURE
• 6. GRAPH:
• Graph is a data structure that consists of a
collection of nodes (vertices) connected by edges.
• Graphs are used to represent relationships
between objects and are widely used in
computer science, mathematics, and other fields.
• Graphs can be used to model a wide variety of
real-world systems, such as social networks,
transportation networks, and computer
networks.
TYPES OF DATA STRUCTURE
LINEAR DATA
STRUCTURES
INTRODUCTION TO
ARRAYS
ARRAY DEFINITION
• An array is a collection of similar data
elements stored at contiguous
memory locations.
• It is the simplest data structure
where each data element can be
accessed directly by only using its
index number.
ARRAY DEFINITION
• For instance, if we want to store the
marks scored by a student in 5
subjects, then there’s no need to
define individual variables for each
subject
• we can define an array that will store
the data elements at contiguous
memory locations.
ARRAY DEFINITION
• Array marks[5] define the marks
scored by a student in 5 different
subjects where each subject’s marks
are located at a particular location in
the array, i.e., marks[0] denote the
marks scored in the first
subject, marks[1] denotes the marks
scored in 2nd subject and so on.
REPRESENTATION OF ARRAY
THE COMPLEXITY OF ARRAY
OPERATIONS
• Time Complexity

Algorithm Average case Worst case


Access O(1) O(1)
Search O(n) O(n)
Insertion O(n) O(n)
Deletion O(n) O(n)
THE COMPLEXITY OF ARRAY
OPERATIONS
• Space Complexity :
The space complexity of an array for
the worst case is O(n).
SINGLE AND MULTIDIMENSIONAL
ARRAYS
• SINGLE / ONE DIMENSIONAL ARRAY:
• Declaration of one dimensional array:
• An array can be declared with the
bracket punctuators [ ], as shown in the
below syntax:
• Data_Type
Array_Name[Number_Of_Elements]
SINGLE / ONE DIMENSIONAL
ARRAY
SINGLE / ONE DIMENSIONAL
ARRAY
• It is a list of the variable of similar data
types
• It allows random access and all the
elements can be accessed with the help
of their index.
• The size of the array is fixed.
• For a dynamically sized array, vector can
be used in C++
INITIALIZING THE ARRAY:
• We can initialize an array in C by assigning value
to each index one by one or by using a single
statement as follows −
int arr[50];
• Example 1 :
• Assign one value each time to the array
int arr[50];
• arr[0]=12;
arr[1]= 43;
arr[2] = 14;
.
.
.
arr[49] = 54;
INITIALIZING THE ARRAY:
• Example 2:
• Using a single statement
• int arr[5] = {10,32,11,45,38};
MULTIDIMENSIONAL
ARRAYS
• We can say a Multidimensional array is
an array of arrays.
• Two Dimensional arrays is also a
multidimensional array.
• In a Multi-Dimensional array, elements of
an array are arranged in the form of rows
and columns.
MULTIDIMENSIONAL
ARRAYS
• Multidimensional array stores
elements in tabular form which is
also known as in row-major order or
column-major order.
MULTIDIMENSIONAL
ARRAYS
• It is a list of lists of the variable of the
same data type.
• It also allows random access and all the
elements can be accessed with the help
of their index.
• It can also be seen as a collection of 1D
arrays. It is also known as the Matrix.
MULTIDIMENSIONAL
ARRAYS
• Its dimension can be increased from 2 to
3 and 4 so on.
• They all are referred to as a multi-
dimensional arrays.
• The most common multidimensional
array is a 2D array.
DECLARATION OF MULTI-
DIMENSIONAL ARRAY

• data_type
array_name[size1][size2]….[sizeN];
data_type: It defines the type of data
that can be held by an array. Here
data_type can be int, char, float. etc.
array_name: Name of the array
size1, size2,… ,sizeN: Sizes of the
dimensions
PICTORIAL REPRESENTATION OF A
MULTIDIMENSIONAL ARRAY
PICTORIAL REPRESENTATION OF A
MULTIDIMENSIONAL ARRAY

• number_of_arrays: number of arrays


which flow in the z-axis
• rows: number of the rows in the y-
axis
• columns: number of the columns
flow in the x-axis
APPLICATION OF ARRAYS
• Storing and accessing data: Arrays are used to
store and retrieve data in a specific order. For
example, an array can be used to store the scores
of a group of students, or the temperatures
recorded by a weather station.
• Sorting: Arrays can be used to sort data in
ascending or descending order. Sorting
algorithms such as bubble sort, merge sort, and
quick sort rely heavily on arrays.
• Searching: Arrays can be searched for specific
elements using algorithms such as linear search and
binary search.
APPLICATION OF ARRAYS
• Matrices: Arrays are used to represent
matrices in mathematical computations such
as matrix multiplication, linear algebra, and
image processing.
• Stacks and queues: Arrays are used as the
underlying data structure for implementing
stacks and queues, which are commonly used
in algorithms and data structures.
APPLICATION OF ARRAYS
• Graphs: Arrays can be used to represent
graphs in computer science. Each element
in the array represents a node in the graph,
and the relationships between the nodes
are represented by the values stored in the
array.
• Dynamic programming: Dynamic
programming algorithms often use arrays to
store intermediate results of sub problems
in order to solve a larger problem.
STACKS
IMPLEMENTATION OF STACK USING
ARRAY
• Stack is a linear data structure that follows the
LIFO (Last In First Out) principle, where it
performs all operations
• It performs insertion and deletion operations
on the stack from only one end from the top
of the stack.
• Inserting a new element on the top of the
stack is known as push operation, and deleting
a data element from the top of the stack is
known as pop operation
IMPLEMENTATION OF STACK USING
ARRAY
• You can perform the
implementation of the stack in
memory using two data
structures: stack implementation
using array and stack
implementation using linked-list.
IMPLEMENTATION OF STACK USING
ARRAY
• In Stack implementation using
arrays, it forms the stack using
the arrays
• All the operations regarding the
stack implementation using
arrays.
IMPLEMENTATION OF STACK USING
ARRAY
OPERATIONS ON
STACK
PUSH OPERATION
• Adding an element on the top of the
stack is termed a push operation
• Push operation has the following two
steps:
– Increment the top variable of the stack so
that it can refer to the next memory
location
– Add a data element at the incremented top
position
PUSH OPERATION
• Stack data structure states an
overflow condition when you try
to insert an element into the
stack when complete.
PUSH OPERATION
PUSH OPERATION
• Algorithm for Push Operation:
• Before pushing the element to the stack, we
check if the stack is full .
• If the stack is full (top == capacity-1) , then Stack
Overflows and we cannot insert the element to
the stack.
• Otherwise, we increment the value of top by
1 (top = top + 1) and the new value is inserted
at top position .
• The elements can be pushed into the stack till we
reach the capacity of the stack.
POP OPERATION
• Removing a data element from the stack
data structure is called a pop operation
• The pop operation has two following
steps:
– The topmost variable of the stack is stored
in another variable, and then the value of
the top variable will be decremented by one
– The pop operation returns the deleted
element that was stored in another variable
as a result.
POP OPERATION
• Stack data structure states an
underflow condition when you try to
delete a data element when the
stack is already empty.
POP OPERATION
POP OPERATION
• Algorithm for Pop Operation:
• Before popping the element from the stack,
we check if the stack is empty .
• If the stack is empty (top == -1), then Stack
Underflows and we cannot remove any
element from the stack.
• Otherwise, we store the value at top,
decrement the value of top by 1 (top = top –
1) and return the stored top value.
PEEK OPERATION
• Peek operations involve returning
the topmost data element of the
stack without removing it from the
stack.
• Underflow conditions may occur if
you try to return the topmost
element if the stack is already empty.
PEEK OPERATION
PEEK OPERATION
• Algorithm for Top Operation:
• Before returning the top element from the
stack, we check if the stack is empty.
• If the stack is empty (top == -1), we simply
print “Stack is empty”.
• Otherwise, we return the element stored
at index = top .
ISEMPTY() OPERATION
• Returns true if the stack is empty, else false.
ISEMPTY() OPERATION
• Algorithm for isEmpty Operation:
• Check for the value of top in stack.
• If (top == -1) , then the stack is empty so
return true .
• Otherwise, the stack is not empty so
return false .
ISFULL() OPERATION
• Returns true if the stack is full, else false.
ISFULL() OPERATION
• Algorithm for isFull Operation:
• Check for the value of top in stack.
• If (top == capacity-1), then the stack is full so
return true.
• Otherwise, the stack is not full so return false.
APPLICATIONS OF STACK
APPLICATIONS OF STACK
• Function Call Management: Stacks are used by
programming languages to manage function calls
and return addresses. When a function is called,
its context is pushed onto the stack, and when
the function returns, it is popped off the stack.
• Undo/Redo functionality: Stacks are often
employed to implement undo and redo
functionality in applications. Each state change is
pushed onto the stack, and you can undo by
popping the top state and redo by pushing the
popped state back onto the stack.
APPLICATIONS OF STACK
• Expression Evaluation: Stacks can be used to
evaluate mathematical expressions, including
infix, postfix, and prefix notations. Operators
and operands are pushed and popped as the
expression is processed.
• Backtracking in algorithms: Stacks are useful
for backtracking algorithms, such as depth-
first search in graph traversal, as they help
keep track of the current path or state.
APPLICATIONS OF STACK
• Memory Management: Stacks are used in
low-level programming for managing the
allocation and deallocation of memory, such
as the call stack in assembly language.
STATIC AND DYNAMIC
REPRESENTATION OF STACK
STATIC AND DYNAMIC
REPRESENTATION OF STACK
• Definition of a Static Stack
• A static stack is a linear data structure
with a fixed, predefined size, wherein
elements are stored and accessed using
the Last In First Out (LIFO) principle.
• Once the static stack is created, its size
remains constant and cannot change
during the program's execution.
STATIC AND DYNAMIC
REPRESENTATION OF STACK
• Definition of a Dynamic Stack
• A dynamic stack, on the other hand, is a
linear data structure with an adjustable
size that can grow or shrink during the
program's execution.
• It still follows the LIFO principle but can
address storage needs more flexibly than
a static stack.
STATIC AND DYNAMIC
REPRESENTATION OF STACK
• Comparison between Static and Dynamic
Stack
1. Memory Allocation
• Static stacks use fixed memory allocation,
which means that their size is determined
during compile time, while dynamic stacks use
dynamic memory allocation, allowing the size
to change during run-time.
• This creates one of the main differences
between the two.
STATIC AND DYNAMIC
REPRESENTATION OF STACK
2. Memory Utilization
• In terms of memory utilization, a static stack
can cause memory wastage if the stack size is
too large, as unused memory cannot be
utilized by other data structures or processes.
• In contrast, a dynamic stack can allocate and
release memory as needed, leading to better
overall memory utilization.
STATIC AND DYNAMIC
REPRESENTATION OF STACK
3. Performance
• Static stacks usually have better performance,
as they have a fixed memory location.
• This allows for faster access and less memory
overhead during execution compared to
dynamic stacks, which need to allocate and
deallocate memory during run-time.
STATIC AND DYNAMIC
REPRESENTATION OF STACK
• Ease of Implementation
• Implementing a static stack is generally
simpler compared to a dynamic stack.
• With a static stack, you only have to define an
array with a fixed size and manage the index
of the top element.
• However, with a dynamic stack, you need to
deal with memory allocation and deallocation
procedures for resizing the stack which makes
implementation more complex.
STATIC AND DYNAMIC
REPRESENTATION OF STACK
• Flexibility
• Dynamic stacks offer greater flexibility, as they
can adjust their size as needed.
• Static stacks, however, have a fixed size which
might lead to insufficient memory when trying
to push new elements onto a full stack, or
wastages when the allocated memory is much
larger than the actual data stored in the stack.
STATIC REPRESENTATION OF STACK
• Refer above slides of Arrays
DYNAMIC REPRESENTATION
OF STACK
DYNAMIC REPRESENTATION OF STACK
• The problem with stack implementation
using an array is working with only a
fixed number of data elements, so we
can also go for stack implementation
using linked-list.
• Linked-list is the data structure that
allocated memory dynamically, but in
both cases, the time complexity is the
same for all the operations like push, pop
and peek.
DYNAMIC REPRESENTATION OF STACK

• Stack implementation using linked-


list, the nodes are maintained in non-
contiguous memory
• Each node contains a pointer to the
immediate next in line node in the
Stack.
DYNAMIC REPRESENTATION OF STACK

• In Stack, implementation using Linked-


List, every new element inserted to the
top of the Stack which means every new
inserting element pointed by the top and
whenever we want to delete element
from the Stack which is pointing to the
top of the Stack by moving the top to is
the previous node in the linked -list.
DYNAMIC REPRESENTATION OF STACK
PUSH OPERATION
• Adding a new node in the Stack is
termed a push operation.
• Pushing a node in the linked list is
quite different from inserting an
element in the array
• Push operation on stack
implementation using linked-list
involves several steps:
PUSH OPERATION
• Create a node first and allocate
memory to it.
• If the list is empty, then the node is
pushed as the first node of the linked
list
• This operation assigns a value to the
data part of the node and gives NULL
to the address part of the node
PUSH OPERATION
• If some nodes are already in the linked
list, then we have to add a new node at
the beginning to the list not to violate
the Stack's property
• For this, assign the element to the
address field of the new node and make
a new node which will be starting node
of the list.
PUSH OPERATION
POP OPERATION
• Deleting a node from the Stack is
known as a pop operation.
• The popping node from the linked
list is different from the popping
element from the array
• To perform the pop operation
involves the following steps:
POP OPERATION
• In Stack, the node is removed from
the end of the linked list.
• Therefore, must delete the value
stored in the head pointer, and the
node must get free
• The following link node will become
the head node now.
POP OPERATION
TRAVERSING
• Displaying all the nodes of a stack
means traversing all the nodes of
linked-list once organized in the form
of a stack
• Traversing involves the following
steps:
TRAVERSING
• Copy the head pointer to the temp
pointer
• Move the temporary pointer through
all the nodes of the list and print the
value field attached to every node
TRAVERSING
QUEUES
ARRAY /STATIC
REPRESENTATION OF
QUEUE
STATIC REPRESENTATION OF
QUEUE
• We can easily represent queue by using
linear arrays
• There are two variables i.e. front and
rear, that are implemented in the case of
every queue
• Front and rear variables point to the
position from where insertions and
deletions are performed in a queue
STATIC REPRESENTATION OF
QUEUE
• Initially, the value of front and queue
is -1 which represents an empty
queue.
• Array representation of a queue
containing 5 elements along with the
respective values of front and rear, is
shown in the following figure.
STATIC REPRESENTATION OF
QUEUE
STATIC REPRESENTATION OF
QUEUE
• The above figure shows the queue of
characters forming the English
word "HELLO“
• Since, No deletion is performed in the
queue till now, therefore the value of
front remains -1
• the value of rear increases by one every
time an insertion is performed in the
queue
STATIC REPRESENTATION OF
QUEUE
• After deleting an element, the value
of front will increase from -1 to 0.
• However, the queue will look
something like following.
STATIC REPRESENTATION OF
QUEUE
LINKED LIST
(DYNAMIC)
REPRESENTATION
OF QUEUE
DYNAMIC REPRESENTATION OF
QUEUE
• The array implementation can
not be used for the large scale
applications where the queues
are implemented
• One of the alternative of array
implementation is linked list
implementation of queue.
DYNAMIC REPRESENTATION OF
QUEUE
• The storage requirement of linked
representation of a queue with n
elements is o(n) while the time
requirement for operations is o(1).
• In a linked queue, each node of the
queue consists of two parts i.e. data
part and the link part.
DYNAMIC REPRESENTATION OF
QUEUE
• Each element of the queue points to its
immediate next element in the memory.
• In the linked queue, there are two
pointers maintained in the memory i.e.
front pointer and rear pointer.
• The front pointer contains the address of
the starting element of the queue while
the rear pointer contains the address of
the last element of the queue.
DYNAMIC REPRESENTATION OF
QUEUE
• Insertion and deletions are
performed at rear and front end
respectively.
• If front and rear both are NULL, it
indicates that the queue is empty.
• The linked representation of queue is
shown in the following figure.
DYNAMIC LIST REPRESENTATION OF
QUEUE
OPERATION ON LINKED QUEUE
• There are two basic operations
which can be implemented on the
linked queues.
• The operations are :
–Insertion
–Deletion.
INSERT OPERATION
• The insert operation append the queue
by adding an element to the end of the
queue.
• The new element will be the last element
of the queue.
• There can be the two scenario of
inserting this new node ptr into the
linked queue.
INSERT OPERATION
• In the first scenario, we insert element into an
empty queue.
• In this case, the condition front =
NULL becomes true
• Now, the new element will be added as the
only element of the queue and the next
pointer of front and rear pointer both, will
point to NULL.
INSERT OPERATION
• In the second case, the queue
contains more than one element
• The condition front = NULL becomes
false
• In this scenario, we need to update
the end pointer rear so that the next
pointer of rear will point to the new
node ptr.
INSERT OPERATION

• Since, this is a linked queue,


hence we also need to make the
rear pointer point to the newly
added node ptr.
• We also need to make the next
pointer of rear point to NULL.
DELETION OPERATION
• Deletion operation removes the element
that is first inserted among all the queue
elements.
• Firstly, we need to check either the list is
empty or not
• The condition front == NULL becomes
true if the list is empty, in this case , we
simply write underflow on the console
and make exit.
DELETION OPERATION
• Otherwise, we will delete the element
that is pointed by the pointer front
• For this purpose, copy the node pointed
by the front pointer into the pointer ptr.
• Now, shift the front pointer, point to its
next node and free the node pointed by
the node ptr.
CIRCULAR QUEUES
CIRCULAR QUEUES
• A Circular Queue is an extended
version of a normal queue where the
last element of the queue is
connected to the first element of the
queue forming a circle.
• The operations are performed based
on FIFO (First In First Out) principle.
• It is also called ‘Ring Buffer’.
CIRCULAR QUEUES
CIRCULAR QUEUES
• In a normal Queue, we can insert
elements until queue becomes full
• But once queue becomes full, we can
not insert the next element even if
there is a space in front of queue.
OPERATIONS ON CIRCULAR QUEUE
• Front(): Get the front item from the
queue.
• Rear(): Get the last item from the
queue.
• enQueue(value) This function is used
to insert an element into the circular
queue. In a circular queue, the new
element is always inserted at the rear
position.
OPERATIONS ON CIRCULAR QUEUE

–Check whether the queue is full –


[i.e., the rear end is in just before the
front end in a circular manner].
• If it is full then display Queue is
full.
• If the queue is not full then, insert
an element at the end of the
queue.
OPERATIONS ON CIRCULAR QUEUE
• deQueue() This function is used to delete
an element from the circular queue. In a
circular queue, the element is always
deleted from the front position.
–Check whether the queue is Empty.
• If it is empty then display Queue is empty
• If the queue is not empty, then get the
first element and remove it from the
queue.
OPERATIONS ON CIRCULAR QUEUE
OPERATIONS ON CIRCULAR QUEUE

• A circular queue can be


implemented using two data
structures:
• Array
• Linked List
COMPLEXITY ANALYSIS OF CIRCULAR
QUEUE OPERATIONS
• Time Complexity:
–Enqueue: O(1) because no loop is
involved for a single enqueue.
–Dequeue: O(1) because no loop is
involved for one dequeue operation.
• Auxiliary Space: O(N) as the queue is
of size N.
APPLICATIONS OF CIRCULAR QUEUE

• Memory Management: The unused


memory locations in the case of ordinary
queues can be utilized in circular queues.
• Traffic system: In computer controlled
traffic system, circular queues are used
to switch on the traffic lights one by one
repeatedly as per the time set.
APPLICATIONS OF CIRCULAR QUEUE

• CPU Scheduling: Operating


systems often maintain a queue
of processes that are ready to
execute or that are waiting for a
particular event to occur.
PRIORITY QUEUE
PRIORITY QUEUES
• A priority queue is an abstract data type
that behaves similarly to the normal
queue except that each element has
some priority, i.e., the element with the
highest priority would come first in a
priority queue
• The priority of the elements in a priority
queue will determine the order in which
elements are removed from the priority
PRIORITY QUEUES
• The priority queue supports only
comparable elements, which means that
the elements are either arranged in an
ascending or descending order.
• For example, suppose we have some
values like 1, 3, 4, 8, 14, 22 inserted in a
priority queue with an ordering imposed
on the values is from least to the
greatest.
PRIORITY QUEUES
• Therefore, the 1 number would be
having the highest priority while 22
will be having the lowest priority.
CHARACTERISTICS OF A PRIORITY
QUEUE
• Every element in a priority queue has
some priority associated with it.
• An element with the higher priority will
be deleted before the deletion of the
lesser priority.
• If two elements in a priority queue have
the same priority, they will be arranged
using the FIFO principle.
CHARACTERISTICS OF A PRIORITY
QUEUE
• Let's understand the priority
queue through an example.
• We have a priority queue that
contains the following values:
• 1, 3, 4, 8, 14, 22
CHARACTERISTICS OF A PRIORITY
QUEUE
• All the values are arranged in ascending
order. Now, we will observe how the
priority queue will look after performing
the following operations:
• poll(): This function will remove the
highest priority element from the priority
queue. In the above priority queue, the
'1' element has the highest priority, so it
will be removed from the priority queue.
CHARACTERISTICS OF A PRIORITY
QUEUE
• add(2): This function will insert '2'
element in a priority queue. As 2 is
the smallest element among all the
numbers so it will obtain the highest
priority.
• poll(): It will remove '2' element
from the priority queue as it has the
highest priority queue.
CHARACTERISTICS OF A PRIORITY
QUEUE
• add(5): It will insert 5 element
after 4 as 5 is larger than 4 and
lesser than 8, so it will obtain the
third highest priority in a priority
queue.
TYPES OF PRIORITY QUEUE

• There are two types of priority


queue:
–Ascending order priority queue
–Descending order priority queue
ASCENDING ORDER PRIORITY QUEUE

• In ascending order priority queue, a


lower priority number is given as a higher
priority in a priority
• For example, we take the numbers from
1 to 5 arranged in an ascending order like
1,2,3,4,5; therefore, the smallest number,
i.e., 1 is given as the highest priority in a
priority queue.
ASCENDING ORDER PRIORITY QUEUE
DESCENDING ORDER PRIORITY
QUEUE
• In descending order priority queue, a
higher priority number is given as a
higher priority in a priority.
• For example, we take the numbers from
1 to 5 arranged in descending order like
5, 4, 3, 2, 1; therefore, the largest
number, i.e., 5 is given as the highest
priority in a priority queue.
DESCENDING ORDER PRIORITY
QUEUE
DESCENDING ORDER PRIORITY
QUEUE
• Let's create the priority queue step by step.
• In the case of priority queue, lower priority
number is considered the higher priority,
i.e., lower priority number = higher priority.
• Step 1: In the list, lower priority number is 1,
whose data value is 300, so it will be inserted
in the list as shown in the below diagram:
DESCENDING ORDER PRIORITY
QUEUE
• Step 2: After inserting 300, priority
number 2 is having a higher priority,
and data values associated with this
priority are 200 and 100. So, this
data will be inserted based on the
FIFO principle; therefore 200 will be
added first and then 100.
DESCENDING ORDER PRIORITY
QUEUE
• Step 3: After inserting the elements of
priority 2, the next higher priority
number is 4 and data elements
associated with 4 priority numbers are
400, 500, 700. In this case, elements
would be inserted based on the FIFO
principle; therefore, 400 will be added
first, then 500, and then 700.
DESCENDING ORDER PRIORITY
QUEUE
• Step 4: After inserting the elements
of priority 4, the next higher priority
number is 5, and the value
associated with priority 5 is 600, so it
will be inserted at the end of the
queue.
DESCENDING ORDER PRIORITY
QUEUE
APPLICATIONS OF PRIORITY QUEUE
• It is used in the Dijkstra's shortest path
algorithm.
• It is used in prim's algorithm
• It is used in data compression techniques
like Huffman code.
• It is used in heap sort.
• It is also used in operating system like
priority scheduling, load balancing and
interrupt hand
CONVERSION OF INFIX TO PREFIX
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• What is infix notation?
• An infix notation is a notation in
which an expression is written in a
usual or normal format
• It is a notation in which the
operators lie between the operands
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• The examples of infix notation are
A+B, A*B, A/B, etc.
• Therefore, the syntax of infix
notation can be written as:
• <operand> <operator> <operand>
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• Parsing Infix expressions:
• In order to parse any expression, we
need to take care of two things,
i.e., Operator
precedence and Associativity
• Operator precedence means the
precedence of any operator over another
operator
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• Precedence order

Operators Symbols

Parenthesis { }, ( ), [ ]

Exponential notation ^

Multiplication and *, /
Division
Addition and +, -
Subtraction
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• Associativity order

Operators Associativity
^ Right to Left
*, / Left to Right
+, - Left to Right
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• What is Prefix notation?
• It is also known as polish notation
• In prefix notation, an operator
comes before the operands. The
syntax of prefix notation is given
below:
• <operator> <operand> <operand>
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• For example, if the infix expression is
5+1, then the prefix expression
corresponding to this infix expression
is +51.
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• If the infix expression is:
• a*b+c
• Convert it into Prefix expression
• Step 1 : a * b + c
• Step 2 : *ab+c
• Step 3 : +*abc
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• Consider another example:
•A+B*C
• Step 1: A + B * C
• Step 2 : A+*BC
• Step 3 : +A*BC
CONVERSION OF INFIX TO
POSTFIX EXPRESSION
CONVERSION OF INFIX TO POSTFIX
EXPRESSION
• Infix expression: The expression of the
form “a operator b” (a + b) i.e., when an
operator is in-between every pair of
operands.
• Postfix expression: The expression of the
form “a b operator” (ab+) i.e., When
every pair of operands is followed by an
operator.
CONVERSION OF INFIX TO POSTFIX
EXPRESSION

• Input: A + B * C + D
Output: ABC*+D+
EVALUATION OF POSTFIX
EXPRESSION USING STACK
Algorithm of Postfix Expression
Evaluation
• Create a stack that holds integer type
data to store the operands of the given
postfix expression. Let it be st.
• Iterate over the string from left to right
and do the following –
– If the current element is an operand, push it
into the stack.
– Otherwise, if the current element is an
operator (say /)do the following -
Algorithm of Postfix Expression
Evaluation
– Pop an element from st, let it be op1.
– Pop another element from st, let it be op2.
– Compute the result of op2 / op1, and push
it into the stack. Note the order i.e. op2 /
op1 should not be changed otherwise it will
affect the final result in some cases.
• At last, st will consist of a single
element i.e. the result after evaluating
the postfix expression.
Algorithm of Postfix Expression
Evaluation
• Let the the postfix expression be 10 22 +
8/6*5+
• Now, proceeding as per the algorithm –
• Create a stack (say st).
• Now since the first element is an
operand, so we will push it in the
stack .i.e. st.push(10). After which stack
looks like -
Algorithm of Postfix Expression
Evaluation

st
10
Algorithm of Postfix Expression
Evaluation
• Now we traverse further in the
postfix expression and found that
the next element is again an
operand. So, we will push it into
the stack, after which the stack
will look like -
Algorithm of Postfix Expression
Evaluation

st
22
10
Algorithm of Postfix Expression
Evaluation
• The next element of the expression is an
operator (+ operator) so we will do the
following –
– Pop an element (say op1) from the stack.
Here op1 = 22.
– Pop another element (say op2) from the
stack. Here op2 = 10.
– Now, we will compute op2 + op1 which
is 32, and push it into the stack. After this
step stack will look like -
Algorithm of Postfix Expression
Evaluation

st
32
Algorithm of Postfix Expression
Evaluation
• On traversing further in the
expression string, we found next
element is an operand. So we will
push it into the stack. Upon doing
this, the stack will look like -
Algorithm of Postfix Expression
Evaluation

st
8
32
Algorithm of Postfix Expression
Evaluation
• The next element is the / operator, so we
will do the following –
– Pop an element (say op1) from the stack.
Here op1 = 8.
– Pop another element (say op2) from the
stack. Here op2 = 32.
– Now, we will compute op2 / op1 which is 4,
and push it into the stack. After this step
stack will look like -
Algorithm of Postfix Expression
Evaluation

st
4
Algorithm of Postfix Expression
Evaluation
• The next element is an
operand, hence pushing it in
the stack. After this step stack
will look like -
Algorithm of Postfix Expression
Evaluation

st
6
4
Algorithm of Postfix Expression
Evaluation
• The next element is the * operator,
hence we need to perform the following
steps -
– Pop an element (say op1) from the stack.
Here op1 = 6.
– Pop another element (say op2) from the
stack. Here op2 = 4.
– Now, we will compute op2 * op1 which
is 24, and push it into the stack. After this
step stack will look like -
Algorithm of Postfix Expression
Evaluation

st
24
Algorithm of Postfix Expression
Evaluation
• The next operator is an operand,
hence pushing it into the stack.
Upon doing which stack will look
like -
Algorithm of Postfix Expression
Evaluation

st
5
24
Algorithm of Postfix Expression
Evaluation
• The last element is the + operator. Hence
it is required to do the following steps -
– Pop an element (say op1) from the stack.
Here op1 = 5.
– Pop another element (say op2) from the
stack. Here op2 = 24.
– Now, we will compute op2 + op1 which
is 29, and push it into the stack. After this
step stack will look like -
Algorithm of Postfix Expression
Evaluation

st
29
Algorithm of Postfix Expression
Evaluation
• Now, we have traversed the
given postfix expression, and
hence as per the algorithm the
only element remaining in the
stack i.e. 29 is the result we
get on evaluating the postfix
expression.
UNIT - II
LINKED LIST
IMPLEMENTATION OF LIST
• A linked list is a fundamental data structure in
computer science.
• It mainly allows
efficient insertion and deletion operations
compared to arrays.
• Like arrays, it is also used to implement other
data structures like stack, queue and deque.
IMPLEMENTATION OF LIST
• What is a Linked List?
• A linked list is a linear data structure that consists
of a series of nodes connected by pointers (in C
or C++) or references (in Java, Python and
JavaScript).
• Each node contains data and
a pointer/reference to the next node in the list.
• Unlike arrays, linked lists allow for
efficient insertion or removal of elements from
any position in the list, as the nodes are not
stored contiguously in memory.
IMPLEMENTATION OF LIST
TYPES OF LINKED LIST
TYPES OF LINKED LIST
• 1. SINGLY LINKED LIST
• It is the simplest type of linked list in which
every node contains some data and a pointer
to the next node of the same data type.
TYPES OF LINKED LIST
• The node contains a pointer to the next
node means that the node stores the
address of the next node in the
sequence.
• A single linked list allows the traversal of
data only in one way.
• Time Complexity: O(N)
Auxiliary Space: O(N)
TYPES OF LINKED LIST
• 2. DOUBLY LINKED LIST
• A doubly linked list or a two-way linked list is a
more complex type of linked list that contains
a pointer to the next as well as the previous
node in sequence.
• Therefore, it contains three parts of data, a
pointer to the next node, and a pointer to the
previous node. This would enable us to
traverse the list in the backward direction as
well. Below is the image for the same:
TYPES OF LINKED LIST
TYPES OF LINKED LIST
• TIME COMPLEXITY:
• The time complexity of the push() function is
O(1)
• The time complexity of the printList() function
is O(n) iswhere n is the number of nodes in
the doubly linked list.
• Space Complexity:
The space complexity of the program is O(n)
as it uses a doubly linked list to store the data,
which requires n nodes
TYPES OF LINKED LIST
• 3. CIRCULAR LINKED LIST
• A circular linked list is that in which the last node
contains the pointer to the first node of the list.
• While traversing a circular linked list, we can
begin at any node and traverse the list in any
direction forward and backward until we reach
the same node we started. Thus, a circular linked
list has no beginning and no end. Below is the
image for the same:
TYPES OF LINKED LIST
TYPES OF LINKED LIST
• Time Complexity:
• Insertion at the beginning of the circular linked list takes O(1) time
complexity.
Traversing and printing all nodes in the circular linked list takes O(n)
time complexity where n is the number of nodes in the linked list.
Therefore, the overall time complexity of the program is O(n).
• Auxiliary Space:
• The space required by the program depends on the number of
nodes in the circular linked list.
In the worst-case scenario, when there are n nodes, the space
complexity of the program will be O(n) as n new nodes will be
created to store the data.
Additionally, some extra space is required for the temporary
variables and the function calls.
Therefore, the auxiliary space complexity of the program is O(n).
TYPES OF LINKED LIST
• 4. DOUBLY CIRCULAR LINKED LIST
• A Doubly Circular linked list or a circular two-way
linked list is a more complex type of linked list
that contains a pointer to the next as well as the
previous node in the sequence.
• The difference between the doubly linked and
circular doubly list is the same as that between a
singly linked list and a circular linked list.
• The circular doubly linked list does not contain
null in the previous field of the first node. Below
is the image for the same:
TYPES OF LINKED LIST
TYPES OF LINKED LIST
• Time Complexity:
• Insertion at the beginning of a doubly circular linked list takes O(1)
time complexity.
Traversing the entire doubly circular linked list takes O(n) time
complexity, where n is the number of nodes in the linked list.
Therefore, the overall time complexity of the program is O(n).
• Auxiliary space:
• The program uses a constant amount of auxiliary space, i.e., O(1),
to create and traverse the doubly circular linked list.
The space required to store the linked list grows linearly with the
number of nodes in the linked list.
Therefore, the overall auxiliary space complexity of the program is
O(1).
OPERATIONS ON LIST
OPERATIONS ON LIST
• These are the following operations on Linked
List :
• 1. Insertion in Linked List
• 2. Search an element in a Linked List
• 3. Find Length of a Linked List
• 4. Reverse a Linked List
• 5. Deletion in Linked List
OPERATIONS ON LIST
• 1. INSERTION IN LINKED LIST :
• Given a Linked List, the task is to insert a new
node in this given Linked List at the following
positions:
a. At the front of the linked list
b. After a given node.
c. At a specific position.
d. At the end of the linked list.
OPERATIONS ON LIST
• A. Insert a Node at the Front/Beginning of
Linked List
• To insert a new node at the front, we create
a new node and point its next reference to
the current head of the linked list. Then, we
update the head to be this new node. This
operation is efficient because it only requires
adjusting a few pointers.
OPERATIONS ON LIST
OPERATIONS ON LIST
• Algorithm:
• Make the first node of Linked List linked to the
new node
• Remove the head from the original first node
of Linked List
• Make the new node as the Head of the Linked
List.
OPERATIONS ON LIST
• B. Insert a Node after a Given Node in Linked
List
• If we want to insert a new node after a
specific node, we first locate that node. Once
we find it, we set the new node’s next
reference to point to the node that follows the
given node. Then, we update the given node’s
next to point to the new node. This requires
traversing the list to find the specified node.
OPERATIONS ON LIST
OPERATIONS ON LIST
• Algorithm:
• Initialize a pointer curr to traverse the list starting from
head.
• Loop through the list to find the node with data equal
to key.
– If not found then return from function.
• Create a new node, say new_node initialized with the
given data.
• Make the next pointer of new_node as next of given
node.
• Update the next pointer of given node point to
the new_node.
OPERATIONS ON LIST
• C. Insert a Node At a Specific Position in
Linked List
• To insert a new node at a specific position, we
need to traverse the list to position – 1. If the
position is valid, we adjust the pointers
similarly such that the next pointer of the new
node points to the next of current
nod and next pointer of current
node points to the new node.
OPERATIONS ON LIST
OPERATIONS ON LIST
• Algorithm:
• Traverse the Linked list upto position-1 nodes.
• Once all the position-1 nodes are traversed,
allocate memory and the given data to the
new node.
• Point the next pointer of the new node to the
next of current node.
• Point the next pointer of current node to the
new node.
OPERATIONS ON LIST
• D. Insert a Node at the End of Linked List
• Inserting at the end involves traversing the
entire list until we reach the last node. We
then set the last node’s next reference to
point to the new node, making the new
node the last element in the list.
OPERATIONS ON LIST
OPERATIONS ON LIST
• Algorithm:
• Go to the last node of the Linked List
• Change the next pointer of last node from
NULL to the new node
• Make the next pointer of new node as NULL to
show the end of Linked List
OPERATIONS ON LIST
• 2. Search an element in a Linked List
• Given a linked list and a key, the task is to check
if key is present in the linked list or not.
• Examples:
• Input: 14 -> 21 -> 11 -> 30 -> 10, key = 14
Output: Yes
Explanation: 14 is present in the linked list.
• Input: 6 -> 21 -> 17 -> 30 -> 10 -> 8, key = 13
Output: No
Explanation: No node in the linked list has value
= 13.
OPERATIONS ON LIST
• The idea is to traverse all the nodes of the linked
list, starting from the head. While traversing, if
we find a node whose value is equal to key then
print “Yes”, otherwise print “No”.
• Algorithm :
• Initialize a node pointer, curr = head.
• Do following while current is not NULL
– If the current value (i.e., curr->key) is equal to the key
being searched return true.
– Otherwise, move to the next node (curr = curr->next).
• If the key is not found, return false
OPERATIONS ON LIST
• 3. Find Length of a Linked List
• Given a Singly Linked List, the task is to find
the Length of the Linked List.
• Examples:
• Input: LinkedList = 1->3->1->2->1
Output: 5
• Input: LinkedList = 2->4->1->9->5->3->6
Output: 7
OPERATIONS ON LIST
• The idea is similar to traversal of Linked List with
an additional variable to count the number of
nodes in the Linked List.
• ALGORITHM:
• Initialize count as 0.
• Initialize a node pointer, curr = head.
• Do following while curr is not NULL
– curr = curr -> next
– Increment count by 1.
• Return count.
OPERATIONS ON LIST
• 4. Reverse a Linked List
• Input: Linked List = 1 -> 2 -> 3 -> 4 -> NULL
Output: Reversed Linked List = 4 -> 3 -> 2 -> 1 ->
NULL
• Input: Linked List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output: Reversed Linked List = 5 -> 4 -> 3 -> 2 -> 1
-> NULL
• Input: Linked List = NULL
Output: Reversed Linked List = NULL
• Input: Linked List = 1->NULL
Output: Reversed Linked List = 1->NULL
OPERATIONS ON LIST
• The idea is to reverse the links of all nodes
using three pointers:
• prev: pointer to keep track of the previous node
• curr: pointer to keep track of the current node
• next: pointer to keep track of the next node
• Starting from the first node, initialize curr with
the head of linked list and next with the next node
of curr. Update the next pointer of curr with prev.
Finally, move the three pointer by
updating prev with curr and curr with next.
OPERATIONS ON LIST
• Follow the steps below to solve the problem:
• Initialize three pointers prev as
NULL, curr as head, and next as NULL.
• Iterate through the linked list. In a loop, do the
following:
– Store the next node, next = curr -> next
– Update the next pointer of curr to prev, curr -> next =
prev
– Update prev as curr and curr as next, prev =
curr and curr = next
OPERATIONS ON LIST
• 5. Deletion in Linked List
• Deleting a node in a Linked List is an important
operation and can be done in three main
ways: removing the first node, removing a
node in the middle, or removing the last node.
OPERATIONS ON LIST
OPERATIONS ON LIST
• Types of Deletion in Linked List
• 1. Deletion at the Beginning of Linked List
• 2. Deletion at Middle of the Linked List
• 3. Deletion at the End of Linked List
OPERATIONS ON LIST
• 1. Deletion at the Beginning of Linked List
• Deletion at the Beginning operation involves
removing the first node of the linked list.
• To perform the deletion at the beginning of
Linked List, we need to change
the head pointer to point to the second node.
If the list is empty, there’s nothing to delete.
OPERATIONS ON LIST
• 2. Deletion at Middle of the Linked List
• Deletion at middle refers to deleting a node
that is neither the first nor the last node in the
linked list.
• To delete a node in the middle, we must first
traverse the list to find the node just before
the one we want to delete. Then, adjust the
pointers to bypass the node being deleted.
OPERATIONS ON LIST
• 3. Deletion at the End of Linked List
• Deletion at the end operation involves
removing the last node of the linked list.
• To perform the deletion at the end of Linked
List, we need to traverse the list to find
the second last node, then set its next pointer
to null. If the list is empty then there is no
node to delete or has only one node then
point head to null.
OPERATIONS ON LIST
• Delete a Linked List node at a given position
• Given a singly linked list and a position (1-
based indexing), the task is to delete a linked
list node at the given position.
• Example:
• Input: position = 2, Linked List = 8->2->3->1->7
Output: Linked List = 8->3->1->7
• Input: position = 1, Linked List = 8->2->3->1->7
Output: Linked List = 2->3->1->7
OPERATIONS ON LIST
• Approach:
• To delete a linked list node at a given position, we have
to starts by checking edge cases like, if the list is empty
(head == NULL) or not, we have to do nothing. After
then, check if the position is the first node, then
updates the head to point its next node, this will
effectively remove the first node. For other positions,
traverses the list to find the node (previous node) just
before the target position, then changes the next
of previous node to target’s next node. If the target
position is greater than the length of given list, it
indicates that the position is not present.
OPERATIONS ON LIST
OPERATIONS ON LIST
• Step-by-step approach:
• If list is empty (head == NULL), returns the head.
• If the position to delete is 1 (the head node):
– Update head = temp->next
• Traverse the list until reaching the desired position:
– Initialize prev to keep track of the previous node.
– Move temp through the list until the position is reached.
• Check for Valid Position:
– If temp becomes NULL, it means the position exceeds the
number of nodes in the list. Print a message and return
the head.
• If the node to delete is found:
– Set prev->next to temp->next, effectively skipping over
the node to be deleted.
APPLICATIONS OF
LINKED LIST
APPLICATIONS OF LINKED LIST
• Applications of Linked Lists:
• Linked Lists can be used to implement stacks,
queue, deque, sparse matrices and adjacency
list representation of graphs.
• Dynamic memory allocation in operating
systems and compilers (linked list of free
blocks).
APPLICATIONS OF LINKED LIST
• Manipulation of polynomials
• Arithmetic operations on long integers.
• In operating systems, they can be used in
Memory management, process scheduling (for
example circular linked list for round robin
scheduling) and file system.
APPLICATIONS OF LINKED LIST
• Algorithms that need to frequently insert or
delete items from large collections of data.
• LRU cache, which uses a doubly linked list to
keep track of the most recently used items in a
cache.
APPLICATIONS OF LINKED LIST
• Applications of Linked Lists in real world:
• The list of songs in the music player are linked
to the previous and next songs.
• In a web browser, previous and next web page
URLs can be linked through the previous and
next buttons (Doubly Linked List)
• In image viewer, the previous and next images
can be linked with the help of the previous
and next buttons (Doubly Linked List)
APPLICATIONS OF LINKED LIST
• Circular Linked Lists can be used to implement
things in round manner where we go to every
element one by one.
• Linked List are preferred over arrays for
implementations of Queue and Deque data
structures because of fast deletions (or
insertions) from the front of the linked lists.
TREES
TREES
• Tree data structure is a specialized data
structure to store data in hierarchical manner.
• It is used to organize and store data in the
computer to be used more effectively.
• It consists of a central node, structural nodes,
and sub-nodes, which are connected via
edges.
• We can also say that tree data structure has
roots, branches, and leaves connected.
TREES
• Tree data structure is a hierarchical structure that
is used to represent and organize data in a way
that is easy to navigate and search.
• It is a collection of nodes that are connected by
edges and has a hierarchical relationship between
the nodes.
• The topmost node of the tree is called the root,
and the nodes below it are called the child nodes.
• Each node can have multiple child nodes, and
these child nodes can also have their own child
nodes, forming a recursive structure.
TREES
• Why Tree is considered a non-linear data
structure?
• The data in a tree are not stored in a
sequential manner i.e., they are not stored
linearly.
• Instead, they are arranged on multiple levels
or we can say it is a hierarchical structure.
• For this reason, the tree is considered to be
a non-linear data structure.
TREES
BASIC
TERMINOLOGIES
BASIC TERMINOLOGIES
• Parent Node: The node which is a predecessor of
a node is called the parent node of that
node. {B} is the parent node of {D, E}.
• Child Node: The node which is the immediate
successor of a node is called the child node of
that node. Examples: {D, E} are the child nodes
of {B}.
• Root Node: The topmost node of a tree or the
node which does not have any parent node is
called the root node. {A} is the root node of the
tree. A non-empty tree must contain exactly one
root node and exactly one path from the root to
all other nodes of the tree.
TREES
• Leaf Node or External Node: The nodes which do
not have any child nodes are called leaf nodes. {I,
J, K, F, G, H} are the leaf nodes of the tree.
• Ancestor of a Node: Any predecessor nodes on
the path of the root to that node are called
Ancestors of that node. {A,B} are the ancestor
nodes of the node {E}
• Descendant: A node x is a descendant of another
node y if and only if y is an ancestor of x.
TREES
• Sibling: Children of the same parent node are
called siblings. {D,E} are called siblings.
• Level of a node: The count of edges on the path
from the root node to that node. The root node
has level 0.
• Internal node: A node with at least one child is
called Internal Node.
• Neighbour of a Node: Parent or child nodes of
that node are called neighbours of that node.
• Subtree: Any node of the tree along with its
descendant.
TREES
TREES
• Tree data structure can be classified into three
types based upon the number of children
each node of the tree can have. The types are:
• BINARY TREE: In a binary tree, each node can
have a maximum of two children linked to it.
Some common types of binary trees include
full binary trees, complete binary trees,
balanced binary trees, and degenerate or
pathological binary trees.
TREES
• TERNARY TREE: A Ternary Tree is a tree data
structure in which each node has at most three
child nodes, usually distinguished as “left”, “mid”
and “right”.
• N-ARY TREE OR GENERIC TREE: Generic trees are
a collection of nodes where each node is a data
structure that consists of records and a list of
references to its children(duplicate references are
not allowed). Unlike the linked list, each node
stores the address of multiple nodes.
OPERATIONS ON BINARY
TREES
OPERATIONS ON BINARY TREES
• What is Binary Tree?
• Binary tree is a tree data structure(non-
linear) in which each node can have at most
two children which are referred to as the left
child and the right child.
• The topmost node in a binary tree is called
the root, and the bottom-most nodes are
called leaves. A binary tree can be visualized
as a hierarchical structure with the root at the
top and the leaves at the bottom.
• Basic Operations on Binary Tree:
1. Tree Traversals (Inorder, Preorder and Postorder)
2. Level Order Tree Traversal
3. Find the Maximum Depth or Height of given
Binary Tree
4. Insertion in a Binary Tree
5. Deletion in a Binary Tree
6. Enumeration of Binary Trees
• TREE TRAVERSALS (INORDER, PREORDER AND
POSTORDER) :
• Tree Traversal Meaning:
• Tree Traversal refers to the process of visiting or accessing
each node of the tree exactly once in a certain order.
• Tree traversal algorithms help us to visit and process all the
nodes of the tree.
• Since tree is not a linear data structure, there are multiple
nodes which we can visit after visiting a certain node.
• There are multiple tree traversal techniques which decide
the order in which the nodes of the tree are to be visited.
• Tree Traversal Techniques:
• A Tree Data Structure can be traversed in
following ways:
• Depth First Search or DFS
– Inorder Traversal
– Preorder Traversal
– Postorder Traversal
• Level Order Traversal or Breadth First Search
or BFS
• INORDER TRAVERSAL:
• Inorder traversal visits the node in the order: Left
-> Root -> Right
• Algorithm for Inorder Traversal:
• Inorder(tree)
• Traverse the left subtree, i.e., call Inorder(left-
>subtree)
• Visit the root.
• Traverse the right subtree, i.e., call Inorder(right-
>subtree)
• PREORDER TRAVERSAL:
• Preorder traversal visits the node in the
order: Root -> Left -> Right
• Algorithm for Preorder Traversal:
• Preorder(tree)
• Visit the root.
• Traverse the left subtree, i.e., call Preorder(left-
>subtree)
• Traverse the right subtree, i.e., call
Preorder(right->subtree)
• POSTORDER TRAVERSAL:
• Postorder traversal visits the node in the
order: Left -> Right -> Root
• Algorithm for Postorder Traversal:
• Algorithm Postorder(tree)
• Traverse the left subtree, i.e., call Postorder(left-
>subtree)
• Traverse the right subtree, i.e., call
Postorder(right->subtree)
• Visit the root
2. LEVEL ORDER TRAVERSAL :
• Level Order Traversal visits all nodes present
in the same level completely before visiting
the next level.
• Algorithm for Level Order Traversal:
• LevelOrder(tree)
• Create an empty queue Q
• Enqueue the root node of the tree to Q
• Loop while Q is not empty
– Dequeue a node from Q and visit it
– Enqueue the left child of the dequeued node if it
exists
– Enqueue the right child of the dequeued node if it
exists
3. FIND THE MAXIMUM DEPTH OR HEIGHT OF
GIVEN BINARY TREE
• Given a binary tree, the task is to find the
maxim depth or height of the tree.
• The height of the tree is the number of
vertices in the tree from the root to the
deepest node.
• Algorithm (Using Recursion):
• Recursively calculate the height of the left and
the right subtrees of a node and assign height
to the node as max of the heights of two
children plus 1. See below the pseudo code
and program for details.
• If the tree is empty then return 0
• Otherwise, do the following -
– Get the max depth of the left subtree
recursively i.e. call maxDepth( tree->left-subtree)
– Get the max depth of the right subtree
recursively i.e. call maxDepth( tree->right-
subtree)
– Get the max of max depths
of left and right subtrees and add 1 to it for the
current node.
• max_depth = max(max_depth of left subtree, max
depth of right subtree) + 1
• Return max_depth.
• Illustration :
APPLICATIONS OF TREES
APPLICATIONS OF TREES
• File System: This allows for efficient
navigation and organization of files.
• Data Compression:Huffman coding is a
popular technique for data compression that
involves constructing a binary tree where the
leaves represent characters and their
frequency of occurrence. The resulting tree is
used to encode the data in a way that
minimizes the amount of storage required.
APPLICATIONS OF TREES
• Compiler Design: In compiler design, a syntax
tree is used to represent the structure of a
program.
• Database Indexing: B-trees and other tree
structures are used in database indexing to
efficiently search for and retrieve data.

You might also like