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

Unit-I DS Data Structures

Unit-I DS Data Structures

Uploaded by

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

Unit-I DS Data Structures

Unit-I DS Data Structures

Uploaded by

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

Unit-I: Introduction to Data Structures

Introduction to Data Structures, abstract data types, Linear list – singly linked list implementation,
insertion, deletion and searching operations on linear list, Stacks- Operations, array and linked
representations of stacks, stack applications, Queues- operations, array and linked representations.

Introduction to Data Structures


 People have been using the term "Data" ever since the invention of computers, to refer to Computer
Information, either transmitted or stored.
 Data can be numbers or texts written on a piece of paper, in the form of bits and bytes stored inside the
memory of electronic devices, or facts stored within a person's mind. As the world started modernizing,
this data became a significant aspect of everyone's day-to-day life, and various implementations allowed
them to store it differently.
 Data is a collection of facts and figures or a set of values or values of a specific format that refers to a
single set of item values.
 Consider the example in the following figure; the items such as ID, Age, Gender, First, Middle, Last,
Street, Locality, etc., are elementary data items. In contrast, the Name and the Address are group data
items.

 Data Structure is a way to store and organize data so that it can be used efficiently. The data structure as
the name indicates is used for organizing the data in memory.
 There are many ways of organizing the data in the memory, one of the data structures which we already
aware is array. Array is a collection of memory elements in which data is stored sequentially, i.e., one
after another. In other words, we can say that array stores the elements in a contiguous manner.
 Some examples of Data Structures are Arrays, Linked Lists, Stack, Queue, Trees, etc. Data Structures
are widely used in almost every aspect of Computer Science, i.e., Compiler Design, Operating Systems,
Graphics, Artificial Intelligence, and many more.
 Data Structures are the main part of many Computer Science Algorithms as they allow the programmers
to manage the data in an effective way. It plays a crucial role in improving the performance of a program
or software, as the main objective of the software is to store and retrieve the user's data as fast as
possible.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Basic Terminologies related to Data Structures
 Data Structures are the building blocks of any software or program. Selecting the suitable data structure
for a program is an extremely challenging task for a programmer.
 The following are some fundamental terminologies used whenever the data structures are involved:
o Data: We can define data as an elementary value or a collection of values. For example, the
Employee's name and ID are the data related to the Employee.
o Data Items: A Single unit of value is known as Data Item.
o Group Items: Data Items that have subordinate data items are known as Group Items. For example,
an employee's name can have a first, middle, and last name.
o Elementary Items: Data Items that are unable to divide into sub-items are known as Elementary
Items. For example, the ID of an Employee.
o Entity and Attribute: A class of certain objects is represented by an Entity. It consists of different
Attributes. Each Attribute symbolizes the specific property of that Entity. For example,

Entities with similar attributes form an Entity Set. Each attribute of an entity set has a range of values,
the set of all possible values that could be assigned to the specific attribute.
o Information: The term "information" is sometimes utilized for data with given attributes of
meaningful or processed data.
o Field: A single elementary unit of information symbolizing the Attribute of an Entity is known as
Field.
o Record: A collection of different data items are known as a Record. For example, if we talk about the
employee entity, then its name, id, address, and job title can be grouped to form the record for the
employee.
o File: A collection of different Records of one entity type is known as a File. For example, if there are
100 employees, there will be 25 records in the related file containing data about each employee.
Need for Data Structures
 As applications are becoming more complex and the amount of data is increasing every day, which may
lead to problems with data searching, processing speed, multiple requests handling, and many more.
 Data Structures support different methods to organize, manage, and store data efficiently. With the help
of Data Structures, we can easily traverse the data items. Data Structures provide Efficiency, Reusability,
and Abstraction.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Why should we learn Data Structures?
 Data Structures and Algorithms are two of the key aspects of Computer Science.
 Data Structures allow us to organize and store data, whereas Algorithms allow us to process that data
meaningfully.
 Learning Data Structures and Algorithms will help us become better Programmers.
 We will be able to write code that is more effective and reliable.
 We will also be able to solve problems more quickly and efficiently.

Key Features of Data Structures


Data Structures will support the following key features:
Correctness: Data Structures are designed to operate correctly for all kinds of inputs based on the
domain of interest. In order words, correctness forms the primary objective of Data Structure, which
always depends upon the problems that the Data Structure is meant to solve.
Efficiency: Data Structures also requires to be efficient. It should process the data quickly without
utilizing many computer resources like memory space. The efficiency of a data structure is a key factor
in determining the success and failure of a program or process.
Robustness: All computer programmers aim to produce software that yields correct output for every
possible input, along with efficient execution on all hardware platforms. This type of robust software
must manage both valid and invalid inputs.
Adaptability: Building software applications like Web Browsers, Word Processors, and Internet Search
Engine include huge software systems that require correct and efficient working or execution for many
years. Moreover, software evolves due to emerging technologies or ever-changing market conditions.
Reusability: The features like Reusability and Adaptability go hand in hand. It is known that the
programmer needs many resources to build any software, making it a costly enterprise. However, if the
software is developed in a reusable and adaptable way, then it can be applied in most future applications.
Thus, by executing quality data structures, it is possible to build reusable software, which appears to be
cost-effective and timesaving.
Classification of Data Structures
 A Data Structure delivers a structured set of variables related to each other in various ways. It forms the
basis of a programming tool that signifies the relationship between the data elements and allows
programmers to process the data efficiently.
 We can classify Data Structures into two categories:
1. Primitive Data Structure
2. Non-Primitive Data Structure
Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN
Email: [email protected], Mob: 8179700193
 The following figure shows the different classifications of Data Structures.

Classifications of Data Structures


Primitive Data Structures
 Primitive Data Structures are the data structures that come in-built into programs. These data structures
can be manipulated or operated directly by machine-level instructions.
 Basic data types like Integer, Float, Character, and Boolean come under the Primitive Data Structures.
 These data types are also called Simple data types, as they contain characters that can't be divided into
further.
Non-Primitive Data Structures
 Non-Primitive Data Structures are those data structures derived from Primitive Data Structures.
 These data structures can't be manipulated or operated directly by machine-level instructions.
 The focus of these data structures is on forming a set of data elements that is either homogeneous (same
data type) or heterogeneous (different data types).
 Based on the structure and arrangement of data, these data structures can be divided into two sub-
categories –
1. Linear Data Structures
2. Non-Linear Data Structures
Linear Data Structures
 A data structure that preserves a linear connection among its data elements is known as a Linear Data
Structure. The arrangement of the data is done linearly, where each element consists of the successors
and predecessors except the first and the last data element. However, it is not necessarily true in the case
of memory, as the arrangement may not be sequential.
 Based on memory allocation, the Linear Data Structures are further classified into two types:
a) Static Data Structures: The data structures having a fixed size are known as Static Data Structures.
The memory for these data structures is allocated at the compiler time, and their size cannot be

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
changed by the user after being compiled; however, the data stored in them can be altered. The Array
is the best example of the Static Data Structure as they have a fixed size, and its data can be modified
later.
b) Dynamic Data Structures: The data structures having a dynamic size are known as Dynamic Data
Structures. The memory of these data structures is allocated at the run time, and their size varies
during the run time of the code. Moreover, the user can change the size as well as the data elements
stored in these data structures at the run time of the code. Linked Lists, Stacks, and Queues are
common examples of dynamic data structures

Non-Linear Data Structures


 Non-Linear Data Structures are data structures where the data elements are not arranged in sequential
order. Here, the insertion and removal of data are not feasible in a linear manner. There exists a
hierarchical relationship between the individual data items.

Types of Non-Linear Data Structures


The following is the list of Non-Linear Data Structures that we generally use:
1. Trees
 A Tree is a Non-Linear Data Structure and a hierarchy containing a collection of nodes such that each
node of the tree stores a value and a list of references to other nodes (the "children").
 The Tree data structure is a specialized method to arrange and collect data in the computer to be utilized
more effectively.
 It contains a central node, structural nodes, and sub-nodes connected via edges. We can also say that the
tree data structure consists of roots, branches, and leaves connected.

A Tree
Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN
Email: [email protected], Mob: 8179700193
Trees can be classified into different types:
Binary Tree: A Tree data structure where each parent node can have at most two children is termed a
Binary Tree.
Binary Search Tree: A Binary Search Tree is a Tree data structure where we can easily maintain a
sorted list of numbers.
AVL Tree: An AVL Tree is a self-balancing Binary Search Tree where each node maintains extra
information known as a Balance Factor whose value is either -1, 0, or +1.
B-Tree: A B-Tree is a special type of self-balancing Binary Search Tree where each node consists of
multiple keys and can have more than two children.

Some Applications of Trees:


 Trees implement hierarchical structures in computer systems like directories and file systems.
 Trees are also used to implement the navigation structure of a website.
 We can generate code like Huffman's code using Trees.
 Trees are also helpful in decision-making in Gaming applications.
 Trees are responsible for implementing priority queues for priority-based OS scheduling functions.
 Trees are also responsible for parsing expressions and statements in the compilers of different
programming languages.
 We can use Trees to store data keys for indexing for Database Management System (DBMS).
 Spanning Trees allows us to route decisions in Computer and Communications Networks.
 Trees are also used in the path-finding algorithm implemented in Artificial Intelligence (AI), Robotics,
and Video Games Applications.

2. Graphs
 A Graph is another example of a Non-Linear Data Structure comprising a finite number of nodes or
vertices and the edges connecting them.
 The Graphs are utilized to address problems of the real world in which it denotes the problem area as a
network such as social networks, circuit networks, and telephone networks. For instance, the nodes or
vertices of a Graph can represent a single user in a telephone network, while the edges represent the link
between them via telephone.
 The Graph data structure, G is considered a mathematical structure comprised of a set of vertices, V and
a set of edges, E as shown below:
G = (V, E)
Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN
Email: [email protected], Mob: 8179700193
A Graph
 The above figure represents a Graph having seven vertices A, B, C, D, E, F, G, and ten edges [A, B], [A,
C], [B, C], [B, D], [B, E], [C, D], [D, E], [D, F], [E, F], and [E, G].
 Depending upon the position of the vertices and edges, the Graphs can be classified into different types:
Null Graph: A Graph with an empty set of edges is termed a Null Graph.
Trivial Graph: A Graph having only one vertex is termed a Trivial Graph.
Simple Graph: A Graph with neither self-loops nor multiple edges is known as a Simple Graph.
Multi Graph: A Graph is said to be Multi if it consists of multiple edges but no self-loops.
Pseudo Graph: A Graph with self-loops and multiple edges is termed a Pseudo Graph.
Non-Directed Graph: A Graph consisting of non-directed edges is known as a Non-Directed Graph.
Directed Graph: A Graph consisting of the directed edges between the vertices is known as a
Directed Graph.
Connected Graph: A Graph with at least a single path between every pair of vertices is termed a
Connected Graph.
Disconnected Graph: A Graph where there does not exist any path between at least one pair of
vertices is termed a Disconnected Graph.
Regular Graph: A Graph where all vertices have the same degree is termed a Regular Graph.
Complete Graph: A Graph in which all vertices have an edge between every pair of vertices is
known as a Complete Graph.
Cycle Graph: A Graph is said to be a Cycle if it has at least three vertices and edges that form a
cycle.
Cyclic Graph: A Graph is said to be Cyclic if and only if at least one cycle exists.
Acyclic Graph: A Graph having zero cycles is termed an Acyclic Graph.
Finite Graph: A Graph with a finite number of vertices and edges is known as a Finite Graph.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Infinite Graph: A Graph with an infinite number of vertices and edges is known as an Infinite
Graph.
Bipartite Graph: A Graph where the vertices can be divided into independent sets A and B, and all
the vertices of set A should only be connected to the vertices present in set B with some edges is
termed a Bipartite Graph.
Planar Graph: A Graph is said to be a Planar if we can draw it in a single plane with two edges
intersecting each other.
Euler Graph: A Graph is said to be Euler if and only if all the vertices are even degrees.
Hamiltonian Graph: A Connected Graph consisting of a Hamiltonian circuit is known as a
Hamiltonian Graph.
Some Applications of Graphs:
 Graphs help us represent routes and networks in transportation, travel, and communication applications.
 Graphs are used to display routes in GPS.
 Graphs also help us represent the interconnections in social networks and other network-based
applications.
 Graphs are utilized in mapping applications.
 Graphs are responsible for the representation of user preference in e-commerce applications.
 Graphs are also used in Utility networks in order to identify the problems posed to local or municipal
corporations.
 Graphs also help to manage the utilization and availability of resources in an organization.
 Graphs are also used to make document link maps of the websites in order to display the connectivity
between the pages through hyperlinks.
 Graphs are also used in robotic motions and neural networks.

Basic Operations of Data Structures


The different types of operations that can be performed to manipulate data in every data structure are:
Traversal: Traversing a data structure means accessing each data element exactly once so it can be
administered. For example, traversing is required while printing the names of all the employees in a
department.
Search: Search is a data structure operation which means to find the location of one or more data
elements that meet certain constraints. Such a data element may or may not be present in the given set of
data elements. For example, we can use the search operation to find the names of all the employees who
have the experience of more than 5 years.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Insertion: Insertion means inserting or adding new data elements to the collection. For example, we can
use the insertion operation to add the details of a new employee the company has recently hired.
Deletion: Deletion means to remove or delete a specific data element from the given list of data
elements. For example, we can use the deleting operation to delete the name of an employee who has left
the job.
Sorting: Sorting means to arrange the data elements in either Ascending or Descending order depending
on the type of application. For example, we can use the sorting operation to arrange the names of
employees in a department in alphabetical order or estimate the top three performers of the month by
arranging the performance of the employees in descending order and extracting the details of the top
three.
Merge: Merge means to combine data elements of two sorted lists in order to form a single list of sorted
data elements.
Create: Create is an operation used to reserve memory for the data elements of the program. This can be
performed using a declaration statement. The creation of data structure can take place either during the
Compile-time or Run-time
The malloc() function is used in C Language to create data structure.
Selection: Selection means selecting a particular data from the available data. We can select any
particular data by specifying conditions inside the loop.
Update: The Update operation allows us to update or modify the data in the data structure. We can also
update any particular data by specifying some conditions inside the loop, like the Selection operation.
Splitting: The Splitting operation allows us to divide data into various subparts decreasing the overall
process completion time.
Abstract Data Type (ADT)
 A data structure is an arrangement of information, generally in the memory, for better algorithm
efficiency. Data Structures include linked lists, stacks, queues, trees, and dictionaries. They could also be
a theoretical entity, like the name and address of a person.
 From the definition mentioned above, we can conclude that the operations in data structure include:
o A high level of abstractions like addition or deletion of an item from a list.
o Searching and sorting an item in a list.
o Accessing the highest priority item in a list.
 Whenever the data structure does such operations, it is known as an Abstract Data Type (ADT).
 Abstract data type can be defined as a set of data elements along with the operations on the data. The
term "abstract" refers to the fact that the data and the fundamental operations defined on it are being

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
studied independently of their implementation. It includes what we can do with the data, not how we
can do it.
 An ADT implementation contains a storage structure in order to store the data elements and algorithms
for fundamental operation. All the data structures, like an array, linked list, queue, stack, etc., are
examples of ADT.
Advantages of using ADTs
 In the real world, programs evolve as a consequence of new constraints or requirements, so modifying a
program generally requires a change in one or multiple data structures. For example, suppose we want to
insert a new field into an employee's record to keep track of more details about each employee. In that
case, we can improve the efficiency of the program by replacing an Array with a Linked structure. In
such a situation, rewriting every procedure that utilizes the modified structure is unsuitable. Hence, a
better alternative is to separate a data structure from its implementation information. This is the principle
behind the usage of Abstract Data Types (ADT).
Applications of Data Structures
The following are some applications of Data Structures:
 Data Structures help in the organization of data in a computer's memory.
 Data Structures also help in representing the information in databases.
 Data Structures allows the implementation of algorithms to search through data (For example, search
engine).
 Data Structures can be used to implement the algorithms to manipulate data (For example, word
processors).
 Data Structures can be used to implement the algorithms to analyze data (For example, data miners).
 Data Structures support algorithms to generate the data (For example, a random number generator).
 Data Structures also support algorithms to compress and decompress the data (For example, a zip
utility).
 Data Structures can be used to implement algorithms to encrypt and decrypt the data (For example, a
security system).
 With the help of Data Structures, software that can manage files and directories can be built (For
example, a file manager).
 Data Structures can be used to develop software that can render graphics. (For example, a web browser
or 3D rendering software).

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
LINEAR LIST
Linked List over Array
Linked list is a data structure that overcomes the limitations of arrays.
Some of the limitations of arrays -
o The size of the array must be known in advance before using it in the program.
o Increasing the size of the array is a time taking process. It is almost impossible to expand the size of
the array at run time.
o All the elements in the array need to be contiguously stored in the memory. Inserting an element in
the array needs shifting of all its predecessors.
Linked list is useful because -
o It allocates the memory dynamically. All the nodes of the linked list are non-contiguously stored in
the memory and linked together with the help of pointers.
o In linked list, size is no longer a problem since we do not need to define its size at the time of
declaration. List grows as per the program's demand and limited to the available memory space.
Linked list
 Linked list is a linear data structure that includes a series of connected nodes.
 Linked list can be defined as the nodes that are randomly stored in the memory.
 A node in the linked list contains two parts, i.e., first is the data part and second is the address part.
The last node of the list contains a pointer to the NULL.
 After array, linked list is the second most used data structure. In a linked list, every link contains a
connection to another node.
Representation of a Linked list
o Linked list can be represented as the connection of nodes in which each node points to the next node
of the list. The representation of the linked list is shown below –

o Linked list contains two parts, and both are of different types, i.e., one is the simple variable (data),
while another is the pointer variable (next). We can declare the linked list by using the user-defined
data type structure (self-referential structure).

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
o The node declaration of linked list is given as follows –

o In the above declaration, a structure named as node is defined that contains two variables, one
is data that is of integer type, and another one is next that is a pointer which contains the address of
next node.
Advantages of Linked list
The advantages of using the Linked list are as follows –
o Dynamic data structure - The size of the linked list may vary according to the requirements. Linked
list does not have a fixed size.
o Insertion and deletion - Unlike arrays, insertion, and deletion in linked list is easier. Array elements
are stored in the consecutive location, whereas the elements in the linked list are stored at a random
location. To insert or delete an element in an array, we have to shift the elements for creating the space.
Whereas, in linked list, instead of shifting, we just have to update the address of the pointer of the
node.
o Memory efficient - The size of a linked list can grow or shrink according to the requirements, so
memory consumption in linked list is efficient.
o Implementation - We can implement both stacks and queues using linked list.
Disadvantages of Linked list
The limitations of using the Linked list are as follows –
o Memory usage - In linked list, node occupies more memory than array. Each node of the linked list
occupies two types of variables, i.e., one is a simple variable, and another one is the pointer variable.
o Traversal - Traversal is not easy in the linked list. If we have to access an element in the linked list,
we cannot access it randomly, while in case of array we can randomly access it by index. For

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
example, if we want to access the 3rd node, then we need to traverse all the nodes before it. So, the
time required to access a particular node is large.
o Reverse traversing - Backtracking or reverse traversing is difficult in a linked list. In a doubly-
linked list, it is easier but requires more memory to store the back pointer.
Uses of Linked List
o The list is not required to be contiguously present in the memory. The node can reside anywhere in
the memory and linked together to make a list. This achieves optimized utilization of space.
o list size is limited to the memory size and doesn't need to be declared in advance.
o Empty node cannot be present in the linked list.
o We can store values of primitive types or objects in the singly linked list.
Applications of Linked list
The applications of the Linked list are as follows -
o With the help of a linked list, the polynomials can be represented as well as we can perform the
operations on the polynomial.
o A linked list can be used to represent the sparse matrix.
o The various operations like student's details, employee's details, or product details can be
implemented using the linked list as the linked list uses the structure data type that can hold different
data types.
o Using linked list, we can implement stack, queue, tree, and other various data structures.
o The graph is a collection of edges and vertices, and the graph can be represented as an adjacency
matrix and adjacency list. If we want to represent the graph as an adjacency matrix, then it can be
implemented as an array. If we want to represent the graph as an adjacency list, then it can be
implemented as a linked list.
o A linked list can be used to implement dynamic memory allocation. The dynamic memory allocation
is the memory allocation done at the run-time.
Complexity of Linked list
The time and space complexity of the linked list for the operations search, insert, and delete.
Time Complexity

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Where 'n' is the number of nodes in the given tree.
Space Complexity

The space complexity of linked list is O(n).


Implementation of Singly Linked List:
o Linked List can be defined as collection of objects called nodes that are randomly stored in the memory.
o A node contains two fields i.e. data stored at that particular address and the pointer which contains the
address of the next node in the memory.
o The last node of the list contains pointer to the NULL.

Node Declaration

Head Declaration

newNode Creation

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Operations performed on Singly Linked list
The basic operations that are supported by a list are mentioned as follows -
o Insertion - This operation is performed to add an element into the list.
o Deletion - It is performed to delete an operation from the list.
o Display - It is performed to display the elements of the list.
o Search - It is performed to search an element from the list using the given key.
Insertion Operation
The insertion into a singly linked list can be performed at different positions. Based on the position of the
new node being inserted, the insertion is categorized into the following categories.
S No. Operation Description
1. Insertion at beginning It involves inserting any element at the front of the list. The
void insertAtBegining(int item); newNode will become as the head of the list.
2. Insertion at end of the list It involves insertion at the last of the linked list. The new
void insertAtEnd(int item); node can be inserted as the only node in the list or it can be
inserted as the last one. Different logics are implemented in
each scenario.
3. Insertion after specified node It involves insertion after the specified node of the linked
void insertRandom(int item); list. Skip the desired number of nodes in order to reach the
node after which the new node will be inserted.
Insertion in Singly Linked List at beginning
o Inserting a new element into a singly linked list at beginning is quite simple. We just need to make a few
adjustments in the node links.
o The following steps need to be followed in order to insert a new node in the list at beginning.
1. Allocate the space for the newNode and store data into the data part of the node.

2. Make the next (link) part of the newNode pointing to the existing first node of the list.

3. At last, make the newNode as the first node of the list.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Algorithm for inserting a newNode at the beginning of the Singly Linked List
Step 1: IF newNode == NULL
WRITE Overflow
GOTO Step 5
[END OF IF]
Step 2: SET newNode → data = item
Step 3: SET newNode → next = head
Step 4: SET head = newNode
Step 5: EXIT

C Function for inserting a newNode at the beginning of the Singly Linked List

Insertion in singly linked list at the end


To insert a node at the end of the SLL, there are two following scenarios which need to be mentioned.
1. The node is being added to an empty list
2. The node is being added to the end of the linked list

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
In the first case:
1. If the condition (head == NULL) gets satisfied. Allocate the space for the newNode by using malloc
statement in C.

2. Set up data and the next (link) part of the newNode.

3. Since, newNode is the only node that will be inserted in the list, make this node pointed by the head
pointer of the list.

In the second case:


1. If the condition (head == NULL) fails, since head is not null. Declare a temporary pointer temp in
order to traverse through the list. temp is made to point the first node of the list.

2. Allocate the space for the newNode by using malloc statement in C. Set up data part of the
newNode.

3. Then, traverse through the entire linked list:

4. At the end of the loop, the temp will be pointing to the last node of the list. Since, the newNode is
going to be the last node of the list, make the next part of this node to point the NULL. Make the
next part of the temp node (which is currently the last node of the list) point to the newNode.

Algorithm for inserting a newNode at the end of the Singly Linked List
Step 1: IF newNode == NULL
WRITE Overflow
GOTO Step 8

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
[END OF IF]
Step 2: SET newNode - > data = item
Step 3: SET newNode - > next = NULL
Step 4: SET temp = head
Step 5: REPEAT Step 6 WHILE temp - > next != NULL
Step 6: SET temp = temp - > next
[END OF LOOP]
Step 7: SET temp - > next = newNode
Step 8: EXIT

C Function for inserting a newNode at the end of the Singly Linked List

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Insertion in singly linked list after a specified Node
1. To insert a node after the specified number of nodes into the linked list, skip the desired number of
nodes in the list to move the temp pointer at the position after which the newNode will be inserted.

2. Allocate the space for the newNode and add the item to the data part of it.

3. Since, at the end of the above loop, the temp pointer would be pointing to the node after which the
newNode will be inserted. Therefore, the next part of the newNode must contain the address of the
next part of the temp (since, newNode will be in between temp and the next of the temp).

4. Make the next part of the temp to point the newNode. This will insert the newNode at the specified
position.

Algorithm for inserting a newNode after a specified Node in singly linked list
Step 1: IF newNode == NULL
WRITE Overflow
GOTO Step 10
END OF IF
Step 2: newNode → data = item
Step 3: SET temp = head
Step 4: SET I = 0

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Step 5: REPEAT Step 6 AND 7 UNTIL I < loc
Step 6: temp = temp → next
Step 7: IF temp == NULL
WRITE "Desired Node not present"
GOTO STEP 10
END OF IF
END OF LOOP
Step 8: newNode → next = temp → next
Step 9: temp → next = newNode
Step 10: EXIT

C Function for inserting a newNode after a specified Node in singly linked list

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Deletion Operation
The Deletion of a node from a singly linked list can be performed at different positions. Based on the
position of the node being deleted, the operation is categorized into the following categories.
S No. Operation Description
1. Deletion from beginning It involves deletion of a node from the beginning of the list.
void deleteFromBegining();
2. Deletion from the end of the list It involves deleting the last node of the list. The list can
void deleteFromEnd(); either be empty or full. Different logic is implemented for
the different scenarios.
3. Deletion after specified node It involves deleting the node after the specified node in the
void deleteRandom(); list. Skip the desired number of nodes to reach the node
after which the node will be deleted. This requires
traversing through the list.

Deletion in singly linked list from beginning


Deleting a node from the beginning of the list is the simplest operation of all.
1. Since the first node of the list is to be deleted, make a temp pointer to point the head node and make
the head to point to the next of the head.

2. free the temp pointer which was pointing to the head node of the list.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Algorithm for deleting a node from the beginning of SLL.
Step 1: IF head == NULL
WRITE Underflow
GOTO Step 5
[END OF IF]
Step 2: SET temp = head
Step 3: SET head = head -> next
Step 4: FREE temp
Step 5: EXIT

C Function for deleting a node from the beginning of SLL.

Deletion in singly linked list from the end


There are two scenarios in which, a node is deleted from the end of the linked list.
1. There is only one node in the list and that needs to be deleted.
2. There is more than one node in the list and the last node of the list needs to be deleted.
In the first case:

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
1. If the condition head → next = NULL is true that means there is only one node, head node available
in the list which needs to be deleted.

In the second case:


1. If the condition head → next = NULL fails, traverse the nodes in order to reach the last node of the
list. To achieve this, declare a temporary pointer temp1 and assign it to head of the list. There is also
a need to keep track of the second last node of the list. For this purpose, declare another pointer
temp2, which will be used in such a way where temp1 will point to the last node then temp2 will
point to the second last node of the list.

2. Now, just need to make the pointer temp2 to point NULL and the last node of the list that is pointed
by temp1 will become free.

Algorithm for deleting a node in singly linked list from the end
Step 1: IF head == NULL
WRITE Underflow
GOTO Step 8
[END OF IF]
Step 2: SET temp1 = head
Step 3: REPEAT Steps 4 and 5 WHILE temp1->next != NULL
Step 4: SET temp2 = temp1
Step 5: SET temp1 = temp1->next
[END OF LOOP]
Step 6: SET temp2->next = NULL
Step 7: FREE temp1
Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN
Email: [email protected], Mob: 8179700193
Step 8: EXIT

C Function for deleting a node in singly linked list from the end

Deletion in singly linked list after the specified node


1. To delete the node, after the specified node, skip the desired number of nodes to reach the node after
which the node will be deleted. There is a need to keep track of the two nodes. The one which is to be

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
deleted and the other one is the node which is present before that node. For this purpose, two pointers
are used: temp1 and temp2.

2. Make the next of temp2 (points to the specified node) point to the next of temp1 (the node which is
to be deleted). And then free the temp1.

Algorithm for deleting a node after the specified node from singly linked list
Step 1: IF head == NULL
WRITE Underflow
GOTO Step 10
END OF IF
Step 2: SET temp1 = head
Step 3: SET I = 0
Step 4: REPEAT Step 5 TO 8 UNTIL I < loc
Step 5: temp2 = temp1
Step 6: temp1 = temp1 → next
Step 7: IF temp == NULL
WRITE "Desired node not present"
GOTO Step 12
END OF IF
Step 8: I = I+1
END OF LOOP
Step 9: temp2 → next = temp1 → next
Step 10: FREE temp1

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Step 11: EXIT

C Function for deleting a node after the specified node from singly linked list

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Traversing and Searching
S No. Operation Description
1. Traversing In traversing, simply visit each node of the list at least once in order to perform some
specific operation on it, for example, printing data part of each node present in the
list.
2. Searching In searching, match each element of the list with the given element. If the element is
found on any of the location, then location of that element is returned otherwise null
is returned.

Traversing in singly linked list


Traversing is the most common operation that is performed in almost every scenario of singly linked list.
1. Traversing means visiting each node of the list once in order to perform some operation on that.

Algorithm for traversing in singly linked list


Step 1: SET temp = head
Step 2: IF temp == NULL
WRITE "SLL is Empty"
GOTO Step 7
END OF IF
Step 4: REPEAT Step 5 AND 6 UNTIL temp != NULL
Step 5: PRINT temp → data
Step 6: temp = temp → next
[END OF LOOP]
Step 7: EXIT

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
C Function for traversing in singly linked list

Searching in singly linked list


Searching is performed to find the location of a particular element in the list. Searching any element in the
list needs traversing through the list and make the comparison of every element of the list with the specified
element. If the element is matched with any of the list element, then the location of the element is returned
from the function.
Algorithm for searching in singly linked list
Step 1: SET temp = head
Step 2: Set I = 0
Step 3: IF temp == NULL
WRITE "SLL is Empty"
GOTO Step 8
END OF IF
Step 4: REPEAT Step 5 TO 7 UNTIL temp != NULL
Step 5: IF temp → data == item

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
WRITE i+1
END OF IF
Step 6: I=I+1
Step 7: temp = temp → next
[END OF LOOP]
Step 8: EXIT

C Function for searching in singly linked list

STACK Data Structure


o A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle.
o Stack has one end, whereas the Queue has two ends (front and rear).

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
o It contains only one pointer top pointer pointing to the topmost element of the stack. Whenever an
element is added in the stack, it is added on the top of the stack, and the element can be deleted only
from top of the stack.
o In other words, a stack can be defined as a container in which insertion and deletion can be done
from the one end known as the top of the stack.
o Inserting an item into the stack is known as push operation, and deleting an item from the stack is
known as pop operation.
Working of Stack
o Stack works on the LIFO pattern. In array implementation of the stack, the stack will have a
maximum limit, as in the following figure the size of the stack is 5.
o To store the elements in a stack and just increment the top of the stack and store the item. let's assume
that stack is empty. We have taken the stack of size 5 as shown below in which we are pushing the
elements one by one until the stack becomes full.

o When new items were entering the stack. The stack gets filled up from the bottom to the top.
o When deletion operation is performed on the stack, as there is only one way for entry and exit as the
other end is closed. It follows the LIFO pattern, which means that the value entered first will be
removed last.
o In the above case, the value 1 is entered first, so it will be removed only after the deletion of all the
other elements.
Standard Stack Operations
The following are some common operations implemented on the stack:
o push(): When we insert an element in a stack then the operation is known as a push. If the stack is
full then the overflow condition occurs.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
o pop(): When we delete an element from the stack, the operation is known as a pop. If the stack is
empty means that no element exists in the stack, this state is known as an underflow state.
o isEmpty(): It determines whether the stack is empty or not.
o isFull(): It determines whether the stack is full or not.'
o peek(): It returns the element at the given position.
o display(): It prints all the elements available in the stack.
PUSH operation
The steps involved in the PUSH operation is given below:
o Before inserting an element in a stack, we check whether the stack is full. If we try to insert the
element in a stack, and the stack is full, then the overflow condition occurs.
o When we initialize a stack, we set the value of top as -1 to check that the stack is empty.
o When the new element is pushed in a stack, first, the value of the top gets incremented,
i.e., top=top+1, and the element will be placed at the new position of the top.
o The elements will be inserted until we reach the max size of the stack.

TWO preconditions which are need to be checked in stack implementation


1. Stack Overflow (isFull())
o When the stack is full (top == max-1) and a push operation is performed on the stack, the
overflow condition will arise. To avoid this condition in every push operation the fullness of the
stack must be checked.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
C Function for checking the fullness of stack (isFull())
Array Implementation Linked List Implementation
o Stack won’t get full in Linked List
implementation. As memory we are allocating
dynamically.

Restricting the overflow condition

2. Stack Underflow (isEmpty())


o When the stack is empty (top==-1) and a pop operation is performed on the stack, the underflow
condition will arise. To avoid this condition in every pop operation the emptiness of the stack must
be checked.
C Function for checking the emptiness of stack (isEmpty())
Array Implementation Linked List Implementation

Restricting the Underflow condition

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
POP operation
The steps involved in the POP operation is given below:
o Before deleting the element from the stack, we check whether the stack is empty. If we try to delete
the element from the empty stack, then the underflow condition occurs.
o If the stack is not empty, we first access the element which is pointed by the top
o Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.

Array implementation of Stack


o In array implementation, the stack is formed by using the array. All the operations of the stack are
performed using arrays indexing.
o Lets understand how each operation can be implemented on the stack using array data structure.
Adding an element onto the stack (push operation)
Adding an element into the top of the stack is referred to as push operation. Push operation involves
following two steps.
1. Increment the variable top so that it can now refer to the next memory location.
2. Add element at the position of incremented top. This is referred to as adding new element at the top
of the stack.
Stack is overflown when we try to insert an element into a completely filled stack therefore, our main
function must always avoid stack overflow condition.
Algorithm for push operation
Step 1: BEGIN
Step 2: IF top == max-1 THEN stack full
Step 3: top = top + 1

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Step 4: stack[top] := item;
Step 5: END
Time Complexity: O(1)

C Function for push operation

Deletion of an element from a stack (Pop operation)


o Deletion of an element from the top of the stack is called pop operation.
o Every time an item is popped from the stack, the value of top will be incremented by 1. The top most
element of the stack is stored in an another variable and then the top is decremented by 1. the
operation returns the deleted value that was stored in another variable as the result.
o The underflow condition occurs when we try to pop an element from an already empty stack.
Algorithm for pop operation
Step 1: BEGIN
Step 2: IF top == -1 THEN stack empty;
Step 3: item := stack[top];
Step 4: top = top - 1;
Step 5: END
Time Complexity: O(1)

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
C Function for pop operation

Visiting top element of the stack (Peek operation)


o Peek operation involves returning the element which is present at the top of the stack without deleting
it. Underflow condition can occur if we try to return the top element in an already empty stack.
Algorithm for peek operation
Step 1: BEGIN
Step 2: IF top == -1 THEN stack empty
Step 3: item = stack[top]
Step 4: RETURN item
Step 5: END
Time Complexity: O(1)

C Function for peek operation

Display the nodes (Traversing)


o Displaying all the nodes of a stack needs traversing all the nodes of the linked list organized in the form
of stack.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
C Function for display operation

Linked list implementation of stack (Using Pointers)


o Instead of using array, linked list can also be used to implement stack.
o Linked list allocates the memory dynamically. However, time complexity in both the scenario is same
for all the operations i.e. push, pop and peek.
o In Linked list implementation of stack, the nodes are maintained non-contiguously in the memory.
Each node contains a pointer (next) to its immediate successor node in the stack. Stack is said to be
overflown if the space left in the memory heap is not enough to create a node.

o The top most node in the stack always contains the address of the top most node in the stack.
o Lets discuss the way in which, each operation is performed in linked list implementation of stack.
Adding a node to the stack (Push operation)
o Adding a node to the stack is referred to as push operation. Pushing an element to a stack in linked
list implementation is different from that of an array implementation.
o No need to check the Overflow condition in linked list implementation of stack. As memory we are
allocating dynamically.
Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN
Email: [email protected], Mob: 8179700193
o In order to push an element onto the stack, the following steps are involved.
1. Create a node first and allocate memory to it.

2. If the SLL is empty (top==NULL) then the item is to be pushed as the start node of the list. This
includes assigning value to the data part of the node and assign null to the address part of the node.

3. If there are some nodes in the list already, then we have to add the new element in the beginning of
the list (to not violate the property of the stack). For this purpose, assign the address of the starting
element to the address field of the new node and make the new node, the starting node of the list.

4. Time Complexity: O(1)

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
C Function to perform push operation

Deleting a node from the stack (POP operation)


o Deleting a node from the top of stack is referred to as pop operation.
o Deleting a node from the linked list implementation of stack is different from that in the array
implementation.
o In order to pop an element from the stack, we need to follow the following steps:

1. Check for the underflow condition: The underflow condition occurs when we try to pop from an
already empty stack. The stack will be empty if the top pointer of the list points to NULL.

2. Adjust the head pointer accordingly: In stack, the elements are popped only from one end, therefore,
the value stored in the top pointer must be deleted and the node must be freed. The next node of the
top node now becomes the new top node.

3. Time Complexity: O(n)

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
C Function to perform pop operation

Display the nodes (Traversing)


o Displaying all the nodes of a stack needs traversing all the nodes of the linked list organized in the form
of stack.
1. Copy the top pointer into a temp pointer.

2. Move the temp pointer through all the nodes of the list and print the value field attached to every
node.

3. Time Complexity: O(n)


Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN
Email: [email protected], Mob: 8179700193
C Function to perform display operation

Visiting top element of the stack (Peek operation)


o Peek operation involves returning the element which is present at the top of the stack without deleting
it. Underflow condition can occur if we try to return the top element in an already empty stack.
Algorithm for peek operation
Step 1: BEGIN
Step 2: IF top == NULL THEN stack empty
Step 3: item = top->data
Step 4: RETURN item
Step 5: END
Time Complexity: O(1)

C Function for peek operation

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
APPLICATIONS OF STACK
1. Reversing a String.
2. Parsing - Balancing of Parenthesis.
3. Infix to Postfix /Prefix conversion.
4. Postfix expression evaluation.
5. Redo-undo features at many places like editors, Photoshop.
6. Recursive function calls and memory management.
7. Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram
problem.
8. Other applications can be Backtracking, Knight tour problem, rat in a maze, N queen problem and
Sudoku solver.
9. In Graph Algorithms like Topological Sorting and Strongly Connected Components.

Infix to Postfix /Prefix conversion


Infix Notation
When the operator is written in between the operands, then it is known as infix notation. Operand does
not have to be always a constant or a variable; it can also be an expression itself.
Syntax of infix notation is given below:
<operand> <operator> <operand>
For example: (p + q) * (r + s)

Postfix notation
A postfix expression is said to be an expression in which the operator appears after the operands.
Syntax of postfix notation is given below:
<operand> <operand> <operator>
For example: AB+ CD+*
Some key points regarding the postfix expression are:
o In postfix expression, operations are performed in the order in which they have written from left to
right.
o It does not any require any parenthesis.
o We do not need to apply operator precedence rules and associativity rules.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Prefix notation
A prefix notation is another form of expression but it does not require other information such as
precedence and associativity, whereas an infix notation requires information of precedence and
associativity. It is also known as polish notation. In prefix notation, an operator comes before the
operands.
Syntax of prefix notation is given below:
<operator> <operand> <operand>
For example: *ab+c

Problem with infix notation


 To evaluate the infix expression, we should know about the operator precedence rules, and if the
operators have the same precedence, then we should follow the associativity rules.
 The use of parenthesis is very important in infix notation to control the order in which the operation to
be performed. Parenthesis improves the readability of the expression.
 An infix expression is the most common way of writing expression, but it is not easy to parse and
evaluate the infix expression without ambiguity. So, mathematicians and logicians studied this problem
and discovered two other ways of writing expressions which are prefix and postfix.
 Both expressions do not require any parenthesis and can be parsed without ambiguity. It does not
require operator precedence and associativity rules.
Infix to Postfix Expression conversion
Algorithm for converting Infix to Postfix:
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
a. If the precedence of the scanned operator is greater than the precedence of the operator in the
stack (or the stack is empty or the stack contains a ‘(‘), push it.
b. Else, Pop all the operators from the stack which are greater than or equal to in precedence
than the scanned operator. (If you encounter parenthesis while popping then stop there and
push the scanned operator in the stack.)
c. After doing that Push the scanned operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered, and discard
both the parenthesis.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it is not empty.
Precedence function to check the operator precedence:

In the algebraic expression, the order of the operator precedence is given in the below table:
Operators Symbols
Parenthesis ( ), {}, [ ]
Exponents ^
Multiplication and Division *, /
Addition and Subtraction +,-

Let's understand through an example.


Infix expression: K + L - M*N + (O^P) * W/U/V * T + Q
Input Expression Stack Postfix Expression
K K
+ +
L + KL
- - K L+
M - K L+ M
* -* K L+ M
N -* KL+MN

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
+ + K L + M N*
K L + M N* -
( +( K L + M N *-
O +( KL+MN*-O
^ +(^ K L + M N* - O
P +(^ K L + M N* - O P
) + K L + M N* - O P ^
* +* K L + M N* - O P ^
W +* K L + M N* - O P ^ W
/ +/ K L + M N* - O P ^ W *
U +/ K L + M N* - O P ^W*U
/ +/ K L + M N* - O P ^W*U/
V +/ KL + MN*-OP^W*U/V
* +* KL+MN*-OP^W*U/V/
T +* KL+MN*-OP^W*U/V/T
+ + KL+MN*-OP^W*U/V/T*
KL+MN*-OP^W*U/V/T*+
Q + KL+MN*-OP^W*U/V/T*Q
KL+MN*-OP^W*U/V/T*+Q+
The final postfix expression of infix expression (K + L - M*N + (O^P) * W/U/V * T + Q) is KL+MN*-
OP^W*U/V/T*+Q+.

Convert the following infix expression into postfix


Example-1: a+b*(c^d-e)^(f+g*h)-i
Solution: abcd^e-fgh*+^*+i-

Infix to Prefix Expression conversion


Algorithm for converting Infix to Prefix:
1. Reverse the infix expression i.e., A+B*C will become C*B+A. Note while reversing each ‘(‘ will
become ‘)’ and each ‘)’ becomes ‘(‘.
2. Obtain the postfix expression of the modified expression i.e., CB*A+.
3. Reverse the postfix expression. Hence in our example prefix is +A*BC.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Let's understand through an example.
Infix Expression: K + L - M * N + (O^P) * W/U/V * T + Q
The Reverse expression would be:
Q + T * V/U/W * (P^O)+ N*M - L + K
Now convert the above expression into postfix form:
Input expression Stack Prefix expression
Q Q
+ + Q
T + QT
* +* QT
V +* QTV
/ +*/ QTV
U +*/ QTVU
/ +*// QTVU
W +*// QTVUW
* +*//* QTVUW
) +*//*) QTVUW
P +*//*) QTVUWP
^ +*//*)^ QTVUWP
O +*//*)^ QTVUWPO
( +*//* QTVUWPO^
+ ++ QTVUWPO^*//*
N ++ QTVUWPO^*//*N
* ++* QTVUWPO^*//*N
M ++* QTVUWPO^*//*NM
- ++- QTVUWPO^*//*NM*
L ++- QTVUWPO^*//*NM*L
+ ++-+ QTVUWPO^*//*NM*L
K ++-+ QTVUWPO^*//*NM*LK
QTVUWPO^*//*NM*LK+-++
The above expression, i.e., QTVUWPO^*//*NM*LK+-++, is not a final expression. Reverse this
expression to obtain the prefix expression: ++-+KL*MN*//*^OPWUVTQ

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Convert the following infix expression into prefix
Infix: A * B + C / D
Prefix: + * A B/ C D
Infix: (A - B/C) * (A/K-L)
Prefix: *-A/BC-/AKL

Prefix to Postfix Expression conversion


Algorithm for converting Prefix Expression to Postfix Expression
Rules for prefix to postfix expression using stack data structure:
 Scan the prefix expression from right to left, i.e., reverse.
 If the incoming symbol is an operand, then push it into the stack.
 If the incoming symbol is an operator, then pop two operands from the stack. Add the incoming
symbol (operator) after the operands. When the operator is added after the operands, then the
expression (as a single symbol) is pushed back into the stack.
 Once the whole expression is scanned, pop and print the postfix expression from the stack.

Let's understand through an example.


Prefix Expression: * - A / B C - / A K L
Reversed Expression: L K A / - C B / A - *
Symbols to Action Stack Description
be scanned
L Push L into the stack L
K Push K into the stack L, K
A Push A into the stack L, K, A
/ Pop A from the stack L, A K / Pop two operands from the stack, i.e., A and
Pop K from the stack K. Add '/' operator after K operand, i.e.,
Push A K / into the stack AK/. Push AK/ into the stack.
- Pop A K / and L from the A K / L - Pop two operands from the stack, i.e., AK/
stack. and L. Add '-' operator after 'L' operand.
Push (A K / L -) into the stack
C Push C into the stack AK/L-,
C

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
B Push B into the stack AK/L-,
C, B
/ Pop B and C from the stack. AK/L-, Pop two operands from the stack, i.e., B and
Push BC/ into the stack. BC/ C. Add '/' operator after C operator, i.e., BC/.
Push BC/ into the stack.
A Push A into the stack AK/L-,
BC/, A
- Pop BC/ and A from the stack. AK/L-, Pop two operands from the stack, i.e., A and
Push ABC/- into the stack. ABC/- BC/. Add '-' operator after '/'.
* Pop ABC/- and AK/L- from ABC/- Pop two operands from the stack, i.e., ABC/-
the stack. Push ABC/AK/L-* AK/L-* , and AK/L- . Add '*' operator after L and '-'
into the stack. operator, i.e., ABC/-AK/L-*.
Resultant Postfix Expression: ABC/-AK/L-*

Postfix to Prefix Expression conversion


Algorithm for converting Postfix Expression to Prefix Expression
The following are the steps used to convert postfix to prefix expression using stack:
o Scan the postfix expression from left to right.
o If the element is an operand, then push it into the stack.
o If the element is an operator, then pop two operands from the stack.
o Create an expression by concatenating two operands and adding operator before the operands.
o Push the result back to the stack.
o Repeat the above steps until we reach the end of the postfix expression.

Let's understand through an example.


If the Postfix expression is given as: AB + CD - *
Symbol Action Stack Description
Scanned
A Push A into the A
stack
B Push B into the AB
stack

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
+ Pop B from the +AB Pop two operands from the stack, i.e., A and B. Add '+'
stack operator before the operands AB, i.e., +AB.
Pop A from the
stack
Push +AB into
the stack.
C Push C into the +ABC
stack
D Push D into the +ABCD
stack
- Pop D from the +AB - Pop two operands from the stack, i.e., D and C. Add '-'
stack. CD operator before the operands CD, i.e., -CD.
Pop C from the
stack.
Push -CD into
the stack
* Pop -CD from *+AB - Pop two operands from the stack, i.e., -CD and +AB. Add
the stack. CD '*' operator before +AB then the expression would become
Pop +AB from *+AB-CD.
the stack.
Push *+AB -CD
into the stack.
The prefix expression of the above postfix expression is *+AB-CD.
Prefix to Infix Expression conversion
Algorithm for Converting Prefix Expression to Infix Expression
 Read the Prefix expression in reverse order (from right to left)
 If the symbol is an operand, then push it onto the Stack
 If the symbol is an operator, then pop two operands from the Stack
Create a string by concatenating the two operands and the operator between them.
string = (operand1 + operator + operand2)
And push the resultant string back to Stack.
 Repeat the above steps until the end of Prefix expression.
 At the end, stack will have only 1 string i.e., resultant string.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Let's understand through an example.

Convert the following Prefix expressions into Infix


Example-1:
Input Prefix: *+ XY - X1Y1
Output Infix: ((X + Y) * (X1 + Y1))
Example-2:
Input Prefix: *+ P / QR -/ STU
Output Infix: ((P - (Q / R)) * ((P / T) - U))
Example-3:
Input Prefix: *+AB-CD
Output Infix: ((A+B)*(C-D))
Example-4:
Input Prefix: *-A/BC-/AKL
Output Infix: ((A-(B/C))*((A/K)-L))

Postfix to Infix Expression conversion


Algorithm for Converting Postfix Expression to Infix Expression
 Read the Postfix expression from left to right.
 If the symbol is an operand, then push it onto the Stack
 If the symbol is an operator, then pop two operands from the Stack
Create a string by concatenating the two operands and the operator between them.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
string = (operand1 + operator + operand2)
And push the resultant string back to Stack.
 Repeat the above steps until the end of Postfix expression.
 At the end, stack will have only 1 string i.e., resultant string.

Convert the following Postfix expressions into Infix


Example-1:
Input: abc++
Output: (a + (b + c))
Example-2:
Input: ab*c+
Output: ((a*b)+c)

Evaluation of Postfix Expression


Algorithm for Evaluating Postfix Expression
1. Create a stack to store operands (or values).
2. Scan the given expression and do following for every scanned element.
….......a) If the element is a number, push it into the stack.
….......b) If the element is an operator, pop operands for the operator from stack.
Evaluate the operator and push the result back to the stack.
3. When the expression is ended, the number in the stack is the final answer.

Let's understand through an example.


If the Postfix expression is given as: “2 3 1 * + 9 –”
Solution:
1. Scan ‘2’, it’s a number, so push it to stack. Stack contains ‘2’.
2. Scan ‘3’, again a number, push it to stack, stack now contains ‘2 3’ (from bottom to top).
3. Scan ‘1’, again a number, push it to stack, stack now contains ‘2 3 1’.
4. Scan ‘*’, it’s an operator, pop two operands from stack, apply the * operator on operands, we get
3*1 which results in 3. We push the result ‘3’ to stack. Stack now becomes ‘2 3’.
5. Scan ‘+’, it’s an operator, pop two operands from stack, apply the + operator on operands, we get 3
+ 2 which results in 5. We push the result ‘5’ to stack. Stack now becomes ‘5’.
6. Scan ‘9’, it’s a number, we push it to the stack. Stack now becomes ‘5 9’.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
7. Scan ‘-’, it’s an operator, pop two operands from stack, apply the – operator on operands, we get 5
– 9 which results in -4. We push the result ‘-4’ to stack. Stack now becomes ‘-4’.
8. There are no more elements to scan, we return the top element from stack (which is the only
element left in stack).

Evaluation of Prefix Expression


Algorithm for Evaluating Prefix Expression
 Step 1: Scan the prefix expression from right to left, i.e., reverse.
 Step 2: If the symbol is an operand, then push it into the stack.
 Step 3: If the symbol is an operator, then pop two operands from the stack. Perform the operation
on these two operands and stores the result back to the stack.
 Step 4: Move to step 2 as long as there are symbols left in the expression.
 Step 5: The final result is stored at the top of the stack and return it.
 Step 6: End

Evaluate the following Prefix expression


Expression: + - * 2 2 / 16 8 5

QUEUE ADT (Abstract Data Type):


o A queue is an abstract data structure that contains a collection of elements.
o A Queue is a linear structure which follows First In First Out (FIFO) order for its operations to be
performed.
o The inserting operation (enQueue) can only be performed from one side (called the rear end) and the
deletion operation (deQueue) can only be performed from the other side (called the front end) of the
queue.
o A good example of a queue is any queue of consumers for a resource where the consumer that came
first is served first (Example: Railway reservation, Movie ticketing, Voters queue during voting and so
on…etc.,).
o The difference between stacks and queues is, in deletion operation the way they perform. In a stack the
item the most recently added will be deleted (poped) first; in a queue the item the least recently added
will be deleted (dequeued) first.
o The regular queue is also known as linear queue. There are other types queues are also possible:
Circular Queues, Priority Queues and Double Ended Queues (or Deque).

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Queue enQueue Operation:

Queue deQueue Operation:

Applications of Queue:
 Queue is used when things don’t have to be processed immediately, but have to be processed in First
In First Out order like Breadth First Search.
 This property of Queue makes it also useful in following kind of scenarios.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
1. When a resource is shared among multiple consumers. Examples include CPU scheduling, Disk
Scheduling.
2. When data is transferred asynchronously (data not necessarily received at same rate as sent)
between two processes. Examples include IO Buffers, pipes, file IO, etc.
Queue ADT
o A Queue contains elements of the same type arranged in sequential order. Operations take place
at both ends, insertion (enQueue) is done at the rear end and deletion (deQueue) is done at the
front end.
o Following operations can be performed:
 enQueue() – Insert an element at the rear end of the queue, if the queue is not full.
 deQueue() – Deletes and return the first element of the queue, if the queue is not empty.
 peekFront() – Return the front element of the queue without removing it, if the queue is not
empty.
 peekRear() – Return the rear element of the queue without removing it, if the queue is not
empty.
 isEmpty() – Return true if the queue is empty, otherwise return false.
 isFull() – Return true if the queue is full, otherwise return false.

TYPES OF QUEUES
There are four different types of queues –

1. Simple Queue or Linear Queue


2. Circular Queue
3. Priority Queue
4. Double Ended Queue (or Deque)
Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN
Email: [email protected], Mob: 8179700193
CIRCULAR QUEUE
Why circular queue?
There was one limitation in the array implementation of Queue. If the rear reaches to the end position of the
Queue, then there might be possibility that some vacant spaces are left in the beginning which cannot be
utilized. So, to overcome such limitations, the concept of the circular queue was introduced.

As it is clear from the above image that, the rear is at the last position of the Queue and front is pointing
somewhere rather than the 0th position. In the above array, there are only two elements and other three
positions are empty. The rear is at the last position of the Queue; if we try to insert the element then it will
show that there are no empty spaces in the Queue. There is one solution to avoid such wastage of memory
space by shifting both the elements at the left and adjust the front and rear end accordingly. It is not a
practically good approach because shifting all the elements will consume lots of time. The efficient approach
to avoid the wastage of the memory is to use the circular queue data structure.
A circular queue is similar to a linear queue as it is also based on the FIFO (First In First Out) principle
except that the last position is connected to the first position in a circular queue that forms a circle. It is also
known as a Ring Buffer.
Operations on Circular Queue
The following are the operations that can be performed on a circular queue:
o peekFront: It is used to get the front element from the Queue.
o peekRear: It is used to get the rear element from the Queue.
o enQueue(value): This function is used to insert the new value in the Queue. The new element is
always inserted from the rear end.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
o deQueue(): This function deletes an element from the Queue. The deletion in a Queue always takes
place from the front end.
Applications of Circular Queue
The circular Queue can be used in the following scenarios:
o Memory management: The circular queue provides memory management. As we have already seen
that in linear queue, the memory is not managed very efficiently. But in case of a circular queue, the
memory is managed efficiently by placing the elements in a location which is unused.
o CPU Scheduling: The operating system also uses the circular queue to insert the processes and then
execute them.
o Traffic system: In a computer-control traffic system, traffic light is one of the best examples of the
circular queue. Each light of traffic light gets ON one by one after every jinterval of time. Like red
light gets ON for one minute then yellow light for one minute and then green light. After green light,
the red light gets ON.

Enqueue operation
The steps of enqueue operation are given below:
o First, we will check whether the Queue is full or not.
o Initially the front and rear are set to -1. When we insert the first element in a Queue, front and rear
both are set to 0.
o When we insert a new element, the rear gets incremented, i.e., rear=rear+1.
Scenarios for inserting an element
There are two scenarios in which queue is not full:
o If rear != max - 1, then rear will be incremented to mod(maxsize) and the new value will be inserted
at the rear end of the queue.
o If front != 0 and rear = max - 1, it means that queue is not full, then set the value of rear to 0 and
insert the new element there.
There are two cases in which the element cannot be inserted:
o When front ==0 && rear = max-1, which means that front is at the first position of the Queue and
rear is at the last position of the Queue.
o front== rear + 1;

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
Algorithm to enQueue an element in a circular queue
Step – 1: IF (rear+1) % max = front
WRITE " Overflow "
GOTO step 4
[END OF IF]
Step – 2: IF front = -1 and rear = -1
SET front = rear = 0
ELSE IF rear = max - 1 and front ! = 0
SET rear = 0
ELSE
SET rear = (rear + 1) % max
[END OF IF]
Step – 3: SET queue[rear] = item
Step – 4: EXIT

Dequeue Operation
The steps of dequeue operation are given below:
o First, we check whether the Queue is empty or not. If the queue is empty, we cannot perform the
dequeue operation.
o When the element is deleted, the value of front gets decremented by 1.
o If there is only one element left which is to be deleted, then the front and rear are reset to -1.

Algorithm to deQueue an element from the circular queue


Step – 1: IF front == -1
WRITE " Underflow "
GOTO Step 4
[END OF IF]
Step – 2: SET item = queue[front]
Step – 3: IF front == REAR
SET front = rear = -1
ELSE
IF front == max -1
SET front = 0

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
ELSE
SET front = front + 1
[END OF IF]
[END OF IF]
Step – 4: EXIT

Priority Queue
o 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 queue.
o The priority queue supports only comparable elements, which means that the elements are either
arranged in an ascending or descending order.
o 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. Therefore, the 1 number would be having
the highest priority while 22 will be having the lowest priority.
Characteristics of a Priority queue
A priority queue is an extension of a queue that contains the following characteristics:
o Every element in a priority queue has some priority associated with it.
o An element with the higher priority will be deleted before the deletion of the lesser priority.
o If two elements in a priority queue have the same priority, they will be arranged using the FIFO
principle.
Types of Priority Queue
There are two types of priority queue:
o 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.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
o 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.

Representation of priority queue


o Now, we will see how to represent the priority queue through a one-way list.
o We will create the priority queue by using the list given below in which INFO list contains the data
elements, PRN list contains the priority numbers of each data element available in the INFO list, and
LINK basically contains the address of the next node.

Deque (or double-ended queue)


o The deque stands for Double Ended Queue. Deque is a linear data structure where the insertion and
deletion operations are performed from both ends. We can say that deque is a generalized version of
the queue.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
o Though the insertion and deletion in a deque can be performed on both ends, it does not follow the
FIFO rule.
o The representation of a deque is given as follows –

Types of deque
There are two types of deque -
o Input restricted queue
o Output restricted queue

Input restricted Queue


o In input restricted queue, insertion operation can be performed at only one end, while deletion can be
performed from both ends.

Output restricted Queue


o In output restricted queue, deletion operation can be performed at only one end, while insertion can
be performed from both ends.

Operations performed on deque


There are the following operations that can be applied on a deque -
o Insertion at front
o Insertion at rear
o Deletion at front
Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN
Email: [email protected], Mob: 8179700193
o Deletion at rear
We can also perform peek operations in the deque along with the operations listed above. Through peek
operation, we can get the deque's front and rear elements of the deque. So, in addition to the above
operations, following operations are also supported in deque -
o Get the front item from the deque
o Get the rear item from the deque
o Check whether the deque is full or not
o Checks whether the deque is empty or not
Now, let's understand the operation performed on deque using an example.
Insertion at the front end
In this operation, the element is inserted from the front end of the queue. Before implementing the operation,
we first have to check whether the queue is full or not. If the queue is not full, then the element can be
inserted from the front end by using the below conditions -
o If the queue is empty, both rear and front are initialized with 0. Now, both will point to the first
element.
o Otherwise, check the position of the front if the front is less than 1 (front < 1), then reinitialize it
by front = max - 1, i.e., the last index of the array.

Insertion at the rear end


In this operation, the element is inserted from the rear end of the queue. Before implementing the operation,
we first have to check again whether the queue is full or not. If the queue is not full, then the element can be
inserted from the rear end by using the below conditions -
o If the queue is empty, both rear and front are initialized with 0. Now, both will point to the first
element.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193
o Otherwise, increment the rear by 1. If the rear is at last index (or max - 1), then instead of increasing
it by 1, we have to make it equal to 0.

Deletion at the front end


In this operation, the element is deleted from the front end of the queue. Before implementing the operation,
we first have to check whether the queue is empty or not. If the queue is empty, i.e., front == -1, it is the
underflow condition, and we cannot perform the deletion. If the queue is not full, then the element can be
inserted from the front end by using the below conditions -
o If the deque has only one element, set rear == -1 and front == -1.
o Else if front is at end (that means front == max - 1), set front = 0.
o Else increment the front by 1, (i.e., front = front + 1).

Deletion at the rear end


In this operation, the element is deleted from the rear end of the queue. Before implementing the operation,
we first have to check whether the queue is empty or not.
o If the queue is empty, i.e., front == -1, it is the underflow condition, and we cannot perform the
deletion.
Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN
Email: [email protected], Mob: 8179700193
o If the deque has only one element, set rear = -1 and front = -1.
o If rear = 0 (rear is at front), then set rear = max - 1.
o Else, decrement the rear by 1 (or, rear = rear -1).

Check empty
This operation is performed to check whether the deque is empty or not. If front == -1, it means that the
deque is empty.
Check full
This operation is performed to check whether the deque is full or not. If front == rear + 1, or front == 0 and
rear == max - 1 it means that the deque is full.
Applications of deque
o Deque can be used as both stack and queue, as it supports both operations.
o Deque can be used as a palindrome checker means that if we read the string from both ends, the string
would be the same.

Mr. Mohammed Afzal, Asst. Professor in CSE (AI&ML) @ SPHN


Email: [email protected], Mob: 8179700193

You might also like