SlideShare a Scribd company logo
1 of 254
UNIT I : Linear Data Structures and Its Applications
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C
Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Syllabus – Unit Wise
4/6/2022 1.1 _ Singly Linked List 2
List of Exercises
4/6/2022 1.1 _ Singly Linked List 3
Text Book and Reference Book
4/6/2022 1.1 _ Singly Linked List 4
4/6/2022 1.1 _ Singly Linked List 5
Unit I : Contents
1. Linked List
2. Doubly Linked List
3. Circular Linked List
4. Applications of List
– Polynomial Addition
– Representing Sparse matrices
5. Reversing a Linked List
6. Cloning a Linked List
7. Sorting of Linked List
8. Applications of Stack
– Towers of Hanoi
– Balancing Parenthesis
– String Reversal
9. Applications of Queue
10. Reversing the Queue using Stack.
4/6/2022 6
1.1 _ Singly Linked List
Classification of Data Structures
4/6/2022 1.1 _ Singly Linked List 7
Linear Data Structures
• In linear data structure, the elements are accessed in a
sequential order.
• But it is not compulsory to store all elements sequentially
(Say, Linked list).
• For Examples,
– Array
– Queue
– Stack
– linked list
• They can be implemented in memory using two ways.
• The first method is by having a linear relationship between
elements by means of sequential memory locations.
• The second method is by having a linear relationship by
using links.
4/6/2022 1.1 _ Singly Linked List 8
Non-Linear Data Structures
• The non-linear data structure does not
organize the data in a sequential manner.
• When the data elements are organised in
some arbitrary fashion without any
sequence, such data structures are called non-
linear data structures.
• For Example,
– Tree
– Graph
4/6/2022 1.1 _ Singly Linked List 9
Linear and Non-Linear
4/6/2022 1.1 _ Singly Linked List 10
Linear and Non-Linear
4/6/2022 1.1 _ Singly Linked List 11
Introduction to Linked List
• A linked list is a linear data structure, in which
the
– elements are not stored at contiguous memory
locations and
– elements are linked using pointers.
• Each element (we will call it as a node) of a list
is comprising of two items :
– data and
– reference to the next node.
4/6/2022 1.1 _ Singly Linked List 12
Introduction to Linked List
• The last node has a reference to null.
• The entry point into a linked list is called the
Head of the list.
• It should be noted that Head is not a separate
node, but the reference to the first node.
• If the list is empty then the Head is a null
reference.
4/6/2022 1.1 _ Singly Linked List 13
Introduction to Linked List
• A linked list is a dynamic data structure.
• The number of nodes in a list is not fixed and can grow
and shrink on demand.
• Any application which has to deal with an unknown
number of objects will need to use a linked list.
• A node in linked list contains two types of fields
namely Data and Next.
• The left part of the node which contains data may
include a simple data type, an array, or a structure.
• The right part of the node contains a pointer to the
next node.
• Linked list is also called a self-referential data type,
since every node contains a pointer to another node
which is of same type.
4/6/2022 1.1 _ Singly Linked List 14
Introduction to Linked List
• A linked list contains a pointer variable, Head, which
stores the address of the first node in the list.
• The entire list can be traversed using this Head
pointer.
• The address of the first node is available in the Head
pointer.
• The address of its succeeding node will be stored in
Next part of the node.
• Using this method, the individual nodes of the list form
a chain of nodes.
• If Head = NULL, means the linked list is empty and
contains no nodes.
4/6/2022 1.1 _ Singly Linked List 15
Linked List Vs Arrays
• Arrays can be used to store linear data of similar types, but arrays have the
following limitations.
• 1) The size of the arrays is fixed: So we must know the upper limit on the
number of elements in advance. Also, generally, the allocated memory is
equal to the upper limit irrespective of the usage.
• 2) Inserting a new element in an array of elements is expensive because
the room has to be created for the new elements and to create room
existing elements have to be shifted.
• For example, in a system, if we maintain a sorted list of IDs in an array id[].
id[] = [1000, 1010, 1050, 2000, 2040].
• And if we want to insert a new ID 1005, then to maintain the sorted order,
we have to move all the elements after 1000 (excluding 1000).
• Deletion is also expensive with arrays until unless some special
techniques are used. For example, to delete 1010 in id[], everything after
1010 has to be moved.
4/6/2022 1.1 _ Singly Linked List 16
Linked List Vs Arrays
• Advantages over arrays
– 1) Dynamic size
– 2) Ease of insertion/deletion
• Drawbacks:
– 1) Random access is not allowed. We have to access
elements sequentially starting from the first node. So we
cannot do binary search with linked lists efficiently with
its default implementation.
– 2) Extra memory space for a pointer is required with each
element of the list.
– 3) Not cache friendly. Since array elements are contiguous
locations, there is locality of reference which is not there
in case of linked lists.
4/6/2022 1.1 _ Singly Linked List 17
Linked List Vs Arrays
• Both arrays and linked lists are a linear collection of data elements.
• But unlike an array, a linked list does not store its nodes in
consecutive memory locations.
• Another difference between an array and a linked list is that a
linked list does not allow random access of data. Nodes in a linked
list can be accessed only in a sequential manner.
• Another advantage of a linked list over an array is that we can add
any number of elements in the list. This is not possible in case of
an array.
• For example, if we declare an integer array as int sno[10], then the
array can store a maximum of 10 data elements and not even one
more than that. There is no such restriction in the case of a linked
list.
• Thus, linked lists provide an efficient way of storing related data and
perform basic operations such as insertion, deletion and updation
of information at the cost of the extra space required for storing the
address of the next node.
4/6/2022 1.1 _ Singly Linked List 18
Linked List Vs Arrays
4/6/2022 1.1 _ Singly Linked List 19
Linked List Vs Arrays
4/6/2022 1.1 _ Singly Linked List 20
Linked List Vs Arrays
• Below Figures gives a pictorial representation showing
how consecutive memory locations are allocated for
array, while in case of linked list random memory
locations are assigned to nodes, but each node is
connected to its next node using pointer.
4/6/2022 1.1 _ Singly Linked List 21
Memory Allocation and Deallocation
for a linked list
• In linked lists, data is stored in the form of
nodes and at runtime memory is allocated for
creating nodes using malloc() function.
4/6/2022 1.1 _ Singly Linked List 22
Memory Allocation and Deallocation
for a linked list
4/6/2022 1.1 _ Singly Linked List 23
4/6/2022 1.1 _ Singly Linked List 24
4/6/2022 1.1 _ Singly Linked List 25
4/6/2022 1.1 _ Singly Linked List 26
4/6/2022 1.1 _ Singly Linked List 27
4/6/2022 1.1 _ Singly Linked List 28
Creating 3 nodes in a linked list and Printing
4/6/2022 1.1 _ Singly Linked List 29
Different types of linked lists
• There are different types of linked lists
available. They are
– Singly linked list
– Doubly linked list
– Circular linked list
4/6/2022 1.1 _ Singly Linked List 30
Singly linked list
• Singly Linked Lists are a type of data structure in which
each node in the list stores the contents and a pointer
or reference to the next node in the list.
• It does not store any pointer or reference to the
previous node.
• To store a singly linked list, only the reference or
pointer to the first node in that list must be stored.
• The last node in a single linked list points to nothing.
• A singly linked list can be traversed in only one
direction from Head to the last node
4/6/2022 1.1 _ Singly Linked List 31
Doubly linked list
• A doubly linked list is a complex type of linked list in which a node
contains a pointer to the previous as well as the next node in the
sequence.
• A doubly linked list consists of data, a pointer to the next node and a
pointer to the previous node.
• The First and last node of a linked list contains a terminator generally a
NULL value, that determines the start and end of the list.
• Doubly linked list is sometimes also referred as bi-directional linked list
since it allows traversal of nodes in both direction.
• Doubly linked list can be used in navigation systems where both front and
back navigation is required. It is used by browsers to implement backward
and forward navigation of visited web pages i.e. back and forward button.
• It is one of the most efficient data structure to implement when
traversing in both direction is required.
• Doubly linked list uses extra memory when compared to array and singly
linked list.
4/6/2022 1.1 _ Singly Linked List 32
Circular linked list
• In a circular linked list, the last node contains a pointer to
the first node of the list.
• It is basically a linear linked list that may be singly or
doubly.
• In the list every node points to the next node and last
node points to the first node, thus forming a circle.
• Since it forms a circle, it is called as a circular linked list.
4/6/2022 1.1 _ Singly Linked List 33
Operations in Linked List
• Creating a List
• Traversing a List
• Adding a Node
• Deleting a Node
4/6/2022 1.1 _ Singly Linked List 34
4/6/2022 1.1 _ Singly Linked List 35
Creating 3 nodes in a linked list and Printing
4/6/2022 1.1 _ Singly Linked List 36
Creating n nodes in a linked list and Traversing
#include <stdio.h>
#include <stdlib.h>
/* Structure of a node */
struct node {
int data; // Data
struct node *next; // Address
}*head;
void createList(int n);
void traverseList();
4/6/2022 1.1 _ Singly Linked List 37
int main()
{
int n;
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);
printf("nData in the list n");
traverseList();
return 0;
}
4/6/2022 1.1 _ Singly Linked List 38
/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int info, i;
head = (struct node *)malloc(sizeof(struct node));
printf("Enter the data of node 1: "); // Input data of node from the user
scanf("%d", &info);
head->data = info; // Link data field with info
head->next = NULL; // Link address field to NULL
4/6/2022 1.1 _ Singly Linked List 39
// Create n - 1 nodes and add to list
temp = head; // to mention temp is the last node in the list
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data of node %d: ", i);
scanf("%d", &info);
newNode->data = info; // Link data field of newNode
newNode->next = NULL; // Make sure new node points to NULL
temp->next = newNode; // Link previous node with newNode
temp = temp->next; // Make current node as previous node
}
}
4/6/2022 1.1 _ Singly Linked List 40
/*
* Display entire list
*/
void traverseList()
{
struct node *temp;
temp = head;
while(temp != NULL)
{
printf("Data = %dn", temp->data); // Print data of current node
temp = temp->next; // Move to next node
}
}
4/6/2022 1.1 _ Singly Linked List 41
Output
Enter the total number of nodes: 3
Enter the data of node 1: 23
Enter the data of node 2: 56
Enter the data of node 3: 89
Data in the list
Data = 23
Data = 56
Data = 89
4/6/2022 1.1 _ Singly Linked List 42
Adding a Node in Linked List
• A new node can be added to the already
existing linked list.
• A node can be added in three different ways.
– At the front of the given linked list
– At the middle of the given linked list
– At the end of the given linked list
4/6/2022 1.1 _ Singly Linked List 43
Insert at the front of the given linked list
• Consider the linked list shown in the Figure.
Suppose we want to add a new node 5 at the
beginning of the list. The following steps will
be done in the linked list to add the node.
4/6/2022 1.1 _ Singly Linked List 44
Step 1
• Step 1: Allocate memory for the new data.
4/6/2022 1.1 _ Singly Linked List 45
Step 2
• Step 2: initialize its data value to 5.
4/6/2022 1.1 _ Singly Linked List 46
Step 3
• Step 3: Add the newly created node as the
first node of the list. Now the Next part of the
new node will contain the address of Head.
4/6/2022 1.1 _ Singly Linked List 47
Step 4
• Step 4: Now assign Head to point to the new
node. Now Head will have the starting
address of the linked list.
4/6/2022 1.1 _ Singly Linked List 48
4/6/2022 1.1 _ Singly Linked List 49
Insert at the middle of the given linked list
• It involves insertion after the specified node of the
linked list. We need to skip the desired number of
nodes in order to reach the node after which the new
node will be inserted. Consider the linked list shown in
Figure. Suppose we want to add a new node 25 after
the node 20 of the given list. The following steps will
be done in the linked list to add the node.
4/6/2022 1.1 _ Singly Linked List 50
Step 1
• Step 1: Allocate memory for the new data.
4/6/2022 1.1 _ Singly Linked List 51
Step 2
• Step 2: initialize its data value to 25.
4/6/2022 1.1 _ Singly Linked List 52
Step 3
• Step 3: Read the element after which you ant
to insert.
4/6/2022 1.1 _ Singly Linked List 53
Step 4
• Step 4: Assign variable ptr to point to Head node.
Move ptr to the next node until the Data part of the
ptr points to 20.
4/6/2022 1.1 _ Singly Linked List 54
Step 5
• Step 5: Assign the NEXT part of the new node
to NEXT part of the ptr.
4/6/2022 1.1 _ Singly Linked List 55
Step 6
• Step 6: Assign the NEXT part of the ptr to new
node.
4/6/2022 1.1 _ Singly Linked List 56
4/6/2022 1.1 _ Singly Linked List 57
4/6/2022 1.1 _ Singly Linked List 58
Insert at the last of the given linked list
• It involves insertion at the last of the linked list. The
new node can be inserted as the only node in the list
or it can be inserted as the last one. Consider the
linked list shown in Figure. Suppose we want to add a
new node 45 at the last of the given list. The following
steps will be done in the linked list to add the node.
4/6/2022 1.1 _ Singly Linked List 59
Step 1
• Step 1: Allocate memory for the new data.
4/6/2022 1.1 _ Singly Linked List 60
Step 2
• Step 2: initialize its data value to 45.
4/6/2022 1.1 _ Singly Linked List 61
Step 3
• Step 3: Assign variable ptr to point to Head node.
Move ptr to the next node until the Next part of the
ptr points to NULL.
4/6/2022 1.1 _ Singly Linked List 62
Step 4
• Step 4: Assign the NEXT part of the new node
to NULL.
4/6/2022 1.1 _ Singly Linked List 63
Step 5
• Step 5: Assign the NEXT part of the ptr to new
node.
4/6/2022 1.1 _ Singly Linked List 64
4/6/2022 1.1 _ Singly Linked List 65
4/6/2022 1.1 _ Singly Linked List 66
Time Complexity
• Time complexity of insert_begin() is O(1) as it
does a constant amount of work.
• Time complexity of insert_middle() is O(1) as it
does a constant amount of work.
• Time complexity of insert_last() is O(n) where n
is the number of nodes in linked list. Since there
is a loop from head to end, the function does
O(n) work.
– This method can also be optimized to work in O(1) by
keeping an extra pointer to the tail of linked list
4/6/2022 1.1 _ Singly Linked List 67
Deleting a Node in Linked List
• A new node can be deleted to the already
existing linked list.
• A node can be deleted in three different ways.
– At the front of the given linked list
– At the middle of the given linked list
– At the end of the given linked list
4/6/2022 1.1 _ Singly Linked List 68
4/6/2022 1.1 _ Singly Linked List 69
Deletion at the front of the given linked list
Deletion at the front of the given linked list
• It involves deletion of a node from the
beginning of the list. Consider the linked list
shown in Figure. Suppose we want to delete
the node at the beginning of the list. The
following steps will be done in the linked list
to delete the node.
4/6/2022 1.1 _ Singly Linked List 70
Step 1
• Step 1: Assign variable ptr to Head node.
4/6/2022 1.1 _ Singly Linked List 71
Step 2
• Step 2: Assign Head to point ptr next.
4/6/2022 1.1 _ Singly Linked List 72
Step 3
• Step 3: Deallocate ptr .
4/6/2022 1.1 _ Singly Linked List 73
4/6/2022 1.1 _ Singly Linked List 74
4/6/2022 1.1 _ Singly Linked List 75
Deletion at the middle of the given linked list
Deletion at the middle of the given linked list
• It involves deletion of a node from the middle
of the list. Consider the linked list shown in
Figure. Suppose we want to delete the node
20 from the given list. The following steps will
be done in the linked list to delete the node.
4/6/2022 1.1 _ Singly Linked List 76
4/6/2022 1.1 _ Singly Linked List 77
4/6/2022 1.1 _ Singly Linked List 78
Deletion at the end of the given linked list
• It involves deletion of the last node from the
list. Consider the linked list shown in Figure.
Suppose we want to delete the last node
from the given list. The following steps will be
done in the linked list to delete the node.
4/6/2022 1.1 _ Singly Linked List 79
4/6/2022 1.1 _ Singly Linked List 80
4/6/2022 1.1 _ Singly Linked List 81
Time Complexity
• Time complexity of delete_begin() is O(1) as it
does a constant amount of work.
• Time complexity of delete_middle() is O(n) as
it does a constant amount of work.
• Time complexity of delete_last() is O(n) where
n is the number of nodes in linked list. Since
there is a loop from head to end, the function
does O(n) work.
4/6/2022 1.1 _ Singly Linked List 82
Thank you
4/6/2022 1.1 _ Singly Linked List 83
1.2 Doubly Linked List
By
Mr.S.Selvaraj,
AP(SRG)/CSE
KEC
Doubly linked lists
🞑 A doubly linked list is a list that can be traversed both from
left to right and from right to left
first
last
🞑 It requires to store two head pointers:
🞑 The first one points to the first element in the list
🞑 The second one points to the last element in the list
Linked lists vs. Doubly linked lists
🞑 Linked lists
🞑 Simple implementation
🞑 Require less memory
🞑 Doubly linked lists
🞑 More complex implementation
🞑 Require more memory
🞑 Accessing elements is easier, since accessing from the “head”
(i.e., leftmost element) costs as much as accessing from the
“tail” (i.e., rightmost element)
🞑 Worst case: accessing the middle element (it requires to go
through half list, both from left and from right)
Creating and printing doubly linked lists
Node definition
🞑 Each node contains:
🞑 The data
🞑 A pointer to the previous element (left-side)
🞑 A pointer to the next element (right-side)
previousPtr data nextPtr
Creating a doubly linked list
🞑 We are going to create a doubly linked list by hand:
first second last
second last
Creating a doubly linked list
🞑 We are going to create a doubly linked list by hand:
first
second last
Creating a doubly linked list
🞑 We are going to create a doubly linked list by hand:
first
THANK YOU
1.3 Circular Linked List
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Circular linked list
• Circular linked list is a linked list where all
nodes are connected to form a circle.
• There is no NULL at the end.
• A circular linked list can be a singly circular
linked list or doubly circular linked list.
4/6/2022 112
1.3 _ Circular Linked List
Circular linked list
4/6/2022 113
1.3 _ Circular Linked List
Circular linked list
• In a circular linked list, the last node contains a pointer to
the first node of the list.
• It is basically a linear linked list that may be singly or
doubly.
• In the list every node points to the next node and last
node points to the first node, thus forming a circle.
• Since it forms a circle, it is called as a circular linked list.
4/6/2022 1.3 _ Circular Linked List 114
1. Any node can be a starting point.
– We can traverse the whole list by starting from
any point.
– We just need to stop when the first visited node
is visited again.
Advantages of Circular linked list
4/6/2022 115
1.3 _ Circular Linked List
Advantages of Circular linked list
2. Useful for implementation of queue.
– Unlike this implementation, we don’t need to
maintain two pointers for front and rear if we
use circular linked list.
– We can maintain a pointer to the last inserted
node and front can always be obtained as next of
last.
4/6/2022 116
1.3 _ Circular Linked List
Advantages of Circular linked list
3. Circular lists are useful in applications to
repeatedly go around the list.
– For example, when multiple applications are running
on a PC.
– It is common for the operating system to put the
running applications on a list and then to cycle
through them, giving each of them a slice of time to
execute, and then making them wait while the CPU is
given to another application.
– It is convenient for the operating system to use a
circular list so that when it reaches the end of the list
it can cycle around to the front of the list.
4/6/2022 117
1.3 _ Circular Linked List
Advantages of Circular linked list
4. Circular Doubly Linked Lists are used for
implementation of advanced data structures
like Fibonacci Heap
4/6/2022 118
1.3 _ Circular Linked List
Adding a node
• Insertion at the beginning: Inserting a new
node as the first node. The next pointer of last
will point to this node and this new node will
point to the previous first node.
4/6/2022 1.3 _ Circular Linked List 119
Operations in Circular Linked List
• Creating a List
• Traversing a List
• Adding a Node
• Deleting a Node
4/6/2022 1.3 _ Circular Linked List 120
4/6/2022 1.3 _ Circular Linked List 121
Creating 3 nodes in a linked list and Printing
4/6/2022 1.3 _ Circular Linked List 122
Creating n nodes in a linked list and Traversing
#include <stdio.h>
#include <stdlib.h>
/* Structure of a node */
struct node {
int data; // Data
struct node *next; // Address
}*head;
void createList(int n);
void traverseList();
4/6/2022 1.3 _ Circular Linked List 123
int main()
{
int n;
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);
printf("nData in the list n");
traverseList();
return 0;
}
4/6/2022 1.3 _ Circular Linked List 124
/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int info, i;
head = (struct node *)malloc(sizeof(struct node));
printf("Enter the data of node 1: "); // Input data of node from the user
scanf("%d", &info);
head->data = info; // Link data field with info
head->next = NULL; // Link address field to NULL
4/6/2022 1.3 _ Circular Linked List 125
// Create n - 1 nodes and add to list
temp = head; // to mention temp is the last node in the list
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data of node %d: ", i);
scanf("%d", &info);
newNode->data = info; // Link data field of newNode
newNode->next = NULL; // Make sure new node points to NULL
temp->next = newNode; // Link previous node with newNode
temp = temp->next; // Make current node as previous node
}
}
4/6/2022 1.3 _ Circular Linked List 126
/*
* Display entire list
*/
void traverseList()
{
struct node *temp;
temp = head;
while(temp != NULL)
{
printf("Data = %dn", temp->data); // Print data of current node
temp = temp->next; // Move to next node
}
}
4/6/2022 1.3 _ Circular Linked List 127
Output
Enter the total number of nodes: 3
Enter the data of node 1: 23
Enter the data of node 2: 56
Enter the data of node 3: 89
Data in the list
Data = 23
Data = 56
Data = 89
4/6/2022 1.3 _ Circular Linked List 128
Adding a Node in Linked List
• A new node can be added to the already
existing linked list.
• A node can be added in three different ways.
– At the front of the given linked list
– At the middle of the given linked list
– At the end of the given linked list
4/6/2022 1.3 _ Circular Linked List 129
Insert at the front of the given linked list
• Consider the linked list shown in the Figure.
Suppose we want to add a new node 5 at the
beginning of the list. The following steps will
be done in the linked list to add the node.
4/6/2022 1.3 _ Circular Linked List 130
Step 1
• Step 1: Allocate memory for the new data.
4/6/2022 1.3 _ Circular Linked List 131
Step 2
• Step 2: initialize its data value to 5.
4/6/2022 1.3 _ Circular Linked List 132
Step 3
• Step 3: Add the newly created node as the
first node of the list. Now the Next part of the
new node will contain the address of Head.
4/6/2022 1.3 _ Circular Linked List 133
Step 4
• Step 4: Now assign Head to point to the new
node. Now Head will have the starting
address of the linked list.
4/6/2022 1.3 _ Circular Linked List 134
4/6/2022 1.3 _ Circular Linked List 135
Insert at the middle of the given linked list
• It involves insertion after the specified node of the
linked list. We need to skip the desired number of
nodes in order to reach the node after which the new
node will be inserted. Consider the linked list shown in
Figure. Suppose we want to add a new node 25 after
the node 20 of the given list. The following steps will
be done in the linked list to add the node.
4/6/2022 1.3 _ Circular Linked List 136
Step 1
• Step 1: Allocate memory for the new data.
4/6/2022 1.3 _ Circular Linked List 137
Step 2
• Step 2: initialize its data value to 25.
4/6/2022 1.3 _ Circular Linked List 138
Step 3
• Step 3: Read the element after which you ant
to insert.
4/6/2022 1.3 _ Circular Linked List 139
Step 4
• Step 4: Assign variable ptr to point to Head node.
Move ptr to the next node until the Data part of the
ptr points to 20.
4/6/2022 1.3 _ Circular Linked List 140
Step 5
• Step 5: Assign the NEXT part of the new node
to NEXT part of the ptr.
4/6/2022 1.3 _ Circular Linked List 141
Step 6
• Step 6: Assign the NEXT part of the ptr to new
node.
4/6/2022 1.3 _ Circular Linked List 142
4/6/2022 1.3 _ Circular Linked List 143
4/6/2022 1.3 _ Circular Linked List 144
Insert at the last of the given linked list
• It involves insertion at the last of the linked list. The
new node can be inserted as the only node in the list
or it can be inserted as the last one. Consider the
linked list shown in Figure. Suppose we want to add a
new node 45 at the last of the given list. The following
steps will be done in the linked list to add the node.
4/6/2022 1.3 _ Circular Linked List 145
Step 1
• Step 1: Allocate memory for the new data.
4/6/2022 1.3 _ Circular Linked List 146
Step 2
• Step 2: initialize its data value to 45.
4/6/2022 1.3 _ Circular Linked List 147
Step 3
• Step 3: Assign variable ptr to point to Head node.
Move ptr to the next node until the Next part of the
ptr points to NULL.
4/6/2022 1.3 _ Circular Linked List 148
Step 4
• Step 4: Assign the NEXT part of the new node
to NULL.
4/6/2022 1.3 _ Circular Linked List 149
Step 5
• Step 5: Assign the NEXT part of the ptr to new
node.
4/6/2022 1.3 _ Circular Linked List 150
4/6/2022 1.3 _ Circular Linked List 151
4/6/2022 1.3 _ Circular Linked List 152
Time Complexity
• Time complexity of insert_begin() is O(1) as it
does a constant amount of work.
• Time complexity of insert_middle() is O(1) as it
does a constant amount of work.
• Time complexity of insert_last() is O(n) where n
is the number of nodes in linked list. Since there
is a loop from head to end, the function does
O(n) work.
– This method can also be optimized to work in O(1) by
keeping an extra pointer to the tail of linked list
4/6/2022 1.3 _ Circular Linked List 153
Deleting a Node in Linked List
• A new node can be deleted to the already
existing linked list.
• A node can be deleted in three different ways.
– At the front of the given linked list
– At the middle of the given linked list
– At the end of the given linked list
4/6/2022 1.3 _ Circular Linked List 154
4/6/2022 1.3 _ Circular Linked List 155
Deletion at the front of the given linked list
1.4 Applications of Linked List
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Unit I : Contents
1. Linked List
2. Doubly Linked List
3. Circular Linked List
4. Applications of List
– Polynomial Addition
– Representing Sparse matrices
5. Reversing a Linked List
6. Cloning a Linked List
7. Sorting of Linked List
8. Applications of Stack
– Towers of Hanoi
– Balancing Parenthesis
– String Reversal
9. Applications of Queue
10. Reversing the Queue using Stack.
4/6/2022 157
1.4 _ Applications of Linked List
Applications of linked list in computer science
• Implementation of stacks and queues.
• Implementation of graphs.
– Adjacency list representation of graphs is most popular
which is uses linked list to store adjacent vertices.
• Dynamic memory allocation.
– We use linked list of free blocks.
• Maintaining directory of names
• Performing arithmetic operations on long integers
• Manipulation of polynomials by storing constants in
the node of linked list
• Representing sparse matrices.
4/6/2022 1.4 _ Applications of Linked List 158
Applications of linked list in real world
• Image viewer
– Previous and next images are linked, hence can be
accessed by next and previous button.
• Previous and next page in web browser
– We can access previous and next URL searched in web
browser by pressing back and next button since, they
are linked as linked list.
• Music Player
– Songs in music player are linked to previous and next
song. you can play songs either from starting or
ending of the list.
4/6/2022 1.4 _ Applications of Linked List 159
Polynomial Addition Using Linked List
• Polynomials and Sparse Matrix are two important
applications of arrays and linked lists.
• A polynomial is composed of different terms where each of
them holds a coefficient and an exponent.
• In mathematics, a polynomial is an expression consisting of
variables (also called indeterminates) and coefficients.
• It involves only the operations of addition, subtraction,
multiplication, and non-negative integer exponentiation of
variables.
• An example of a polynomial of a single indeterminate x is x2
− 4x + 7.
• An example in three variables is x3 + 2xyz2 − yz + 1.
4/6/2022 1.4 _ Applications of Linked List 160
What is Polynomial?
• A polynomial p(x) is the expression in variable
x which is in the form (axn + bxn-1 + …. + jx+ k).
– where a, b, c …., k fall in the category of real
numbers and
– 'n' is non negative integer, which is called the
degree of polynomial.
4/6/2022 1.4 _ Applications of Linked List 161
characteristic of the polynomial
• An essential characteristic of the polynomial is
that each term in the polynomial expression
consists of two parts:
– one is the coefficient
– other is the exponent
• Example :
– 10x2 + 26x
– Here 10 and 26 are coefficients and
– 2, 1 is its exponential value.
4/6/2022 1.4 _ Applications of Linked List 162
Points to keep in mind while working
with Polynomials
• The sign of each coefficient and exponent is
stored within the coefficient and the exponent
itself.
• Additional terms having equal exponent is
possible one.
• The storage allocation for each term in the
polynomial must be done in ascending and
descending order of their exponent.
4/6/2022 1.4 _ Applications of Linked List 163
Representing Polynomial Equation in
Linked List
4/6/2022 1.4 _ Applications of Linked List 164
Polynomial Addition
4/6/2022 1.4 _ Applications of Linked List 165
Polynomial Node Structure
4/6/2022 1.4 _ Applications of Linked List 166
Sparse Matrix
• A matrix is a two-dimensional data object made of m
rows and n columns, therefore having total m x n
values. If most of the elements of the matrix have 0
value, then it is called a sparse matrix.
• Why to use Sparse Matrix instead of simple matrix ?
– Storage: There are lesser non-zero elements than zeros
and thus lesser memory can be used to store only those
elements.
– Computing time: Computing time can be saved by logically
designing a data structure traversing only non-zero
elements.
4/6/2022 1.4 _ Applications of Linked List 167
Sparse Matrix
4/6/2022 1.4 _ Applications of Linked List 168
Thank you
4/6/2022 1.4 _ Applications of Linked List 169
1.5 Reversing a Linked List
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Unit I : Contents
1. Linked List
2. Doubly Linked List
3. Circular Linked List
4. Applications of List
– Polynomial Addition
– Representing Sparse matrices
5. Reversing a Linked List
6. Cloning a Linked List
7. Sorting of Linked List
8. Applications of Stack
– Towers of Hanoi
– Balancing Parenthesis
– String Reversal
9. Applications of Queue
10. Reversing the Queue using Stack.
4/6/2022 171
1.4 _ Applications of Linked List
Reversing a list
4/6/2022 1.4 _ Applications of Linked List 172
Reversing a list
• Using array method
• Using recursive method
• Using iterative method
4/6/2022 1.4 _ Applications of Linked List 173
Using array method
4/6/2022 1.4 _ Applications of Linked List 174
Using array method
4/6/2022 1.4 _ Applications of Linked List 175
Using array method
4/6/2022 1.4 _ Applications of Linked List 176
Using array method
4/6/2022 1.4 _ Applications of Linked List 177
Recursive Function
4/6/2022 1.4 _ Applications of Linked List 178
Structure of recursive function
4/6/2022 1.4 _ Applications of Linked List 179
Structure of recursive function
4/6/2022 1.4 _ Applications of Linked List 180
Execution of Factorial Function
4/6/2022 1.4 _ Applications of Linked List 181
Execution of Factorial Function
4/6/2022 1.4 _ Applications of Linked List 182
Execution of Factorial Function
4/6/2022 1.4 _ Applications of Linked List 183
Recursive Function Examples
4/6/2022 1.4 _ Applications of Linked List 184
Using Recursive Method
void reverse(struct node *ptr1); // Function Prototype
int main()
{
createList(n);
printf("nData in the list n");
traverseList();
reverse(head); // Function call or initial recursive call
return 0;
}
void reverse(struct node *ptr1) // Function definition
{
if(ptr1==NULL) // Base case
{
return;
}
else
{
reverse(ptr1->next); // Progressive case
printf("%dn",ptr1->data);
}
}
4/6/2022 1.4 _ Applications of Linked List 185
Using iterative method
• Given pointer to the head node of a linked list, the task is to reverse
the linked list.
• We need to reverse the list by changing the links between nodes.
• Step 1:Initialize three pointers
– prev as NULL,
– curr as head and
– next as NULL.
• Step 2: Iterate through the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = curr->next
// Now change next of current
// This is where actual reversing happens
curr->next = prev
// Move prev and curr one step forward
prev = curr
curr = next
4/6/2022 1.4 _ Applications of Linked List 186
Using iterative method
4/6/2022 1.4 _ Applications of Linked List 187
Using iterative method
static void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next = NULL;
while (current != NULL) {
// Store next
next = current->next;
// Reverse current node's pointer
current->next = prev;
// Move pointers one position ahead.
prev = current;
current = next;
}
*head_ref = prev;
}
4/6/2022 1.4 _ Applications of Linked List 188
Thank you
4/6/2022 1.4 _ Applications of Linked List 189
1.6 Cloning / Copying a Linked List
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Unit I : Contents
1. Linked List
2. Doubly Linked List
3. Circular Linked List
4. Applications of List
– Polynomial Addition
– Representing Sparse matrices
5. Reversing a Linked List
6. Cloning/Copying a Linked List
7. Sorting of Linked List
8. Applications of Stack
– Towers of Hanoi
– Balancing Parenthesis
– String Reversal
9. Applications of Queue
10. Reversing the Queue using Stack.
4/6/2022 191
1.4 _ Clone / Copy a Linked List
Cloning / Copying a linked list
4/6/2022 1.4 _ Clone / Copy a Linked List 192
4/6/2022 1.4 _ Clone / Copy a Linked List 193
4/6/2022 1.4 _ Clone / Copy a Linked List 194
4/6/2022 1.4 _ Clone / Copy a Linked List 195
4/6/2022 1.4 _ Clone / Copy a Linked List 196
4/6/2022 1.4 _ Clone / Copy a Linked List 197
Thank you
4/6/2022 1.4 _ Clone / Copy a Linked List 198
1.7 Searching and Sorting a Linked List
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Unit I : Contents
1. Linked List
2. Doubly Linked List
3. Circular Linked List
4. Applications of List
– Polynomial Addition
– Representing Sparse matrices
5. Reversing a Linked List
6. Cloning a Linked List
7. Searching and Sorting of Linked List
8. Applications of Stack
– Towers of Hanoi
– Balancing Parenthesis
– String Reversal
9. Applications of Queue
10. Reversing the Queue using Stack.
4/6/2022 200
1.4 _ Searching and Sorting of Linked List
Searching a List
• Searching is performed in order 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.
4/6/2022 1.4 _ Searching and Sorting of Linked List 201
Types of Search
• Linear Search
• Binary Search
4/6/2022 1.4 _ Searching and Sorting of Linked List 202
Linear Search
• Linear search is the simplest search algorithm
and often called sequential search.
• In this type of searching, we simply traverse the
list completely and match each element of the
list with the item whose location is to be found.
• If the match found then location of the item is
returned otherwise the algorithm return NULL.
• Linear search is mostly used to search an
unordered list in which the items are not sorted.
4/6/2022 1.4 _ Searching and Sorting of Linked List 203
Linear Search
4/6/2022 1.4 _ Searching and Sorting of Linked List 204
void search()
{
struct node *temp1;
int value,flag,i=0;
temp1=head;
printf("Enter the value you want to search:");
scanf("%d",&value);
while(temp1 !=NULL)
{
if(temp1->data==value)
{
printf("Yes %d is present at location %d",value,i+1);
flag=0;
}
else
{
flag=1;
}
i++;
temp1=temp1->next;
}
if(flag!=0)
{
printf("No %d is not present",value);
}
}
4/6/2022 1.4 _ Searching and Sorting of Linked List 205
Search an element
in a linked list
Binary Search
• Binary search is the search technique which works
efficiently on the sorted lists.
• Hence, in order to search an element into some list by
using binary search technique, we must ensure that
the list is sorted.
• Binary search follows divide and conquer approach in
which, the list is divided into two halves and the item
is compared with the middle element of the list.
• If the match is found then, the location of middle
element is returned otherwise, we search into either of
the halves depending upon the result produced
through the match.
4/6/2022 1.4 _ Searching and Sorting of Linked List 206
4/6/2022 1.4 _ Searching and Sorting of Linked List 207
Binary Search
4/6/2022 1.4 _ Searching and Sorting of Linked List 208
Sorting a List
4/6/2022 1.4 _ Searching and Sorting of Linked List 209
Sorting a List
• Many sorting algorithms available:
– Bubble sort
– Insertion sort
– Merge sort
– Quick sort
– Etc..
4/6/2022 1.4 _ Searching and Sorting of Linked List 210
Sorting a List – using bubble sort
• To accomplish this task, we maintain two pointers: ptr1 and
ptr2.
• Initially,
– ptr1 point to head node and
– ptr2 will point to node next to ptr1.
• Traverse through the list till ptr1 points to null, by
comparing ptr1's data with ptr2's data.
• If ptr1's data is greater than the ptr2's data, then swap
data between them.
• In the above example,
– ptr1 will initially point to 9 and ptr2 will point to 7.
– Since, 9 is greater than 7, swap the data.
• Continue this process until the entire list is sorted in
ascending order
4/6/2022 1.4 _ Searching and Sorting of Linked List 211
void bubblesort()
{
struct node *ptr1,*ptr2;
int temp;
ptr1 = head;
while (ptr1!=NULL)
{
ptr2=ptr1->next;
while(ptr2!= NULL)
{
if (ptr1->data > ptr2->data)
{
temp = ptr1->data;
ptr1->data=ptr2->data;
ptr2->data=temp;
}
ptr2 = ptr2->next;
}
ptr1 = ptr1->next;
}
}
4/6/2022 1.4 _ Searching and Sorting of Linked List 212
Sorting a List
– using
bubble sort
Thank you
4/6/2022 1.4 _ Searching and Sorting of Linked List 213
1.8 Applications of Stack
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Unit I : Contents
1. Linked List
2. Doubly Linked List
3. Circular Linked List
4. Applications of List
– Polynomial Addition
– Representing Sparse matrices
5. Reversing a Linked List
6. Cloning a Linked List
7. Sorting of Linked List
8. Applications of Stack
– Towers of Hanoi
– Balancing Parenthesis
– String Reversal
9. Applications of Queue
10. Reversing the Queue using Stack.
4/6/2022 215
1.8 _ Applications of Stack
Applications of Stack
• Balancing of symbols
• Infix to Postfix /Prefix conversion
• Redo-undo features at many places like editors, photoshop.
• Forward and backward feature in web browsers
• Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem,
histogram problem.
• Backtracking is one of the algorithm designing technique .Some example of back
tracking are Knight-Tour problem, N-Queen problem, find your way through maze
and game like chess or checkers in all this problems we dive into someway if that
way is not efficient we come back to the previous state and go into some another
path. To get back from current state we need to store the previous state for that
purpose we need stack.
• In Graph Algorithms like Topological Sorting and Strongly Connected Components
• In Memory management any modern computer uses stack as the primary-
management for a running purpose. Each program that is running in a computer
system has its own memory allocations
• String reversal is also a another application of stack. Here one by one each
character get inserted into the stack. So the first character of string is on the
bottom of the stack and the last element of string is on the top of stack. After
Performing the pop operations on stack we get string in reverse order .
4/6/2022 1.8 _ Applications of Stack 216
Some Applications in this unit
• Applications of Stack
– Infix to Postfix / Prefix Conversion
– Towers of Hanoi
– Balancing Parenthesis
– String Reversal
4/6/2022 1.8 _ Applications of Stack 217
Infix, Prefix, Postfix Expression
• Infix expression:
– An expression is called the Infix expression if the operator
appears in between the operands in the expression.
– Simply of the form (operand1 operator operand2).
– Operators are written in-between their operands.
X + Y
A * ( B + C ) / D
• Prefix expression (also known as "Polish notation"):
– An expression is called the Prefix expression if the
operator appears before the operands in the expression.
– Simply of the form (operator operand1 operand2).
– Operators are written before their operands.
+ X Y
/ * A + B C D
4/6/2022 218
1.8 _ Applications of Stack
Infix, Prefix, Postfix Expression
• Postfix expression (also known as "Reverse
Polish notation"):
– An expression is called the postfix expression if the
operator appears in the expression after the
operands.
– Simply of the form (operand1 operand2 operator).
– Operators are written after their operands.
X Y +
A B C + * D /
4/6/2022 219
1.8 _ Applications of Stack
Infix, Prefix, Postfix Expression
4/6/2022 220
1.8 _ Applications of Stack
Infix to Postfix Conversion
Algorithm
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
…..3.1 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.
…..3.2 Else, Pop all the operators from the stack which are
greater than or equal to in precedence than that of the
scanned operator. After doing that Push the scanned
operator to the stack. (If you encounter parenthesis while
popping then stop there and push the scanned operator in
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 all
the operators until a ‘(‘ is encountered, and discard both
the parenthesis.
6. Repeat steps 2-6 until infix expression is scanned.
7. Print the output
8. Pop and output from the stack until it is not empty.
4/6/2022 221
1.8 _ Applications of Stack
An illustration
• First, the symbol a is read, so it is passed through to the output. Then '+' is
read and pushed onto the stack.
• Next b is read and passed through to the output
• Next a '*' is read. The top entry on the operator stack has lower
precedence than '*', so nothing is output and '*' is put on the stack.
• Next, c is read and output.
4/6/2022 222
1.8 _ Applications of Stack
An illustration
• The next symbol is a '+'. Checking the stack, we find that we
will pop a '*' and place it on the output, pop the other '+',
which is not of lower but equal priority, on the stack, and then
push the '+'.
• The next symbol read is an '(', which, being of highest
precedence, is placed on the stack. Then d is read and output.
4/6/2022 223
1.8 _ Applications of Stack
An illustration
• We continue by reading a '*'. Since open parentheses do not
get removed except when a closed parenthesis is being
processed, there is no output. Next, e is read and output.
• The next symbol read is a '+'. We pop and output '*' and then
push '+'. Then we read and output
4/6/2022 224
1.8 _ Applications of Stack
An illustration
• Now we read a ')', so the stack is emptied back to the '('. We
output a '+'.
• We read a '*' next; it is pushed onto the stack. Then g is read
and output.
4/6/2022 225
1.8 _ Applications of Stack
An illustration
• The input is now empty, so we pop and output symbols from
the stack until it is empty.
4/6/2022 226
1.8 _ Applications of Stack
4/6/2022 227
1.8 _ Applications of Stack
4/6/2022 228
1.8 _ Applications of Stack
4/6/2022 229
1.8 _ Applications of Stack
PROBLEM
1. 3+4*5/6
2. (300+23)*(43-21)/(84+7)
3. (4+8)*(6-5)/((3-2)*(2+2))
4/6/2022 230
1.8 _ Applications of Stack
ANSWER
1. 3 4 5 * 6 / +
2. 300 23 + 43 21 -* 84 7 + /
3. 4 8 + 6 5 -* 3 2 –2 2 + * /
4/6/2022 231
1.8 _ Applications of Stack
Problems
1) Infix : (A+B) * (C-D)
Infix to Postfix : AB+CD-*
2) Infix : A-(B/C)*(A/K)-L
Infix to Postfix : ABC/-AK/L-*
4/6/2022 232
1.8 _ Applications of Stack
Expression Evaluation
The simple algorithm uses a stack and is as follows:
1. Make an empty stack.
2. Read an input string.
3. Read characters one by one until end of string is
encountered.
4. If the character is a digit, convert it into an integer
and push onto the stack.
5. If the character is not a digit, pop two numbers from
the stack and perform the corresponding operation
and push the result onto the stack.
6. At end of the string, pop the result from the stack
4/6/2022 233
1.8 _ Applications of Stack
ILLUSTRATION
4/6/2022
Next '+' is read, so 3 and 2 are popped from the stack and their sum, 5, is pushed.
Next 8 is pushed.
234
1.8 _ Applications of Stack
4/6/2022
Now '*' is read, so 8 and 5 are popped as 8 * 5 = 40 is pushed.
235
1.8 _ Applications of Stack
4/6/2022 236
1.8 _ Applications of Stack
PROBLEM
1. 3+4*5/6
2. (300+23)*(43-21)/(84+7)
3. (4+8)*(6-5)/((3-2)*(2+2))
4/6/2022 237
1.8 _ Applications of Stack
Tower of Hanoi
• The tower of Hanoi is a mathematical puzzle.
• It consists of three rods and a number of disks of different
sizes which can slide onto any rod.
• The puzzle starts with the disks in a neat stack in ascending
order of size on one rod, the smallest at the top.
• We have to obtain the same stack on the third rod.
• The objective of the puzzle is to move the entire stack to
another rod, obeying the following simple rules−
– Only one disk can be moved at a time.
– Each move consists of taking the upper disk from one of the
stacks and placing it on top of another stack i.e. a disk can only
be moved if it is the uppermost disk on a stack.
– No disk may be placed on top of a smaller disk.
4/6/2022 1.8 _ Applications of Stack 238
Example - TOH
4/6/2022 1.8 _ Applications of Stack 239
Basic Steps and Algorithm for TOH
4/6/2022 1.8 _ Applications of Stack 240
Recursive Program for Tower of Hanoi
4/6/2022 1.8 _ Applications of Stack 241
Balancing Parenthesis
• Given an expression string exp, write a
program to examine whether the pairs and
the orders of
– “{“, “}”,
– “(“, “)”,
– “[“, “]” are correct in exp.
4/6/2022 1.8 _ Applications of Stack 242
Example
4/6/2022 1.8 _ Applications of Stack 243
Algorithm
• Declare a character stack S.
• Now traverse the expression string exp.
– If the current character is a starting bracket (‘(‘ or ‘{‘
or ‘[‘) then push it to stack.
– If the current character is a closing bracket (‘)’ or ‘}’ or
‘]’) then pop from stack and if the popped character is
the matching starting bracket then fine else brackets
are not balanced.
• After complete traversal, if there is some starting
bracket left in stack then “not balanced”
4/6/2022 1.8 _ Applications of Stack 244
4/6/2022 1.8 _ Applications of Stack 245
String Reverse
• Given a string, reverse it using stack. For
example “KONGU” should be converted to
“UGNOK”.
• Following is simple algorithm to reverse a
string using stack.
– Create an empty stack.
– One by one push all characters of string to stack.
– One by one pop all characters from stack and put
them back to string.
4/6/2022 1.8 _ Applications of Stack 246
Thank you
4/6/2022 1.8 _ Applications of Stack 247
1.8 Applications of Queue and Reverse the Queue
using Stack
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Unit I : Contents
1. Linked List
2. Doubly Linked List
3. Circular Linked List
4. Applications of List
– Polynomial Addition
– Representing Sparse matrices
5. Reversing a Linked List
6. Cloning a Linked List
7. Sorting of Linked List
8. Applications of Stack
– Towers of Hanoi
– Balancing Parenthesis
– String Reversal
9. Applications of Queue
10. Reversing the Queue using Stack.
4/6/2022 249
1.9 _ Applications of Queue and Reverse
Queue
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.
• 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.
3) In Operating systems:
a) Semaphores
b) FCFS ( first come first serve) scheduling, example: FIFO queue
c) Spooling in printers
d) Buffer for devices like keyboard
4) In Networks:
a) Queues in routers/ switches
b) Mail Queues
5) Variations: (Deque, Priority Queue, Doubly Ended Priority
Queue )
4/6/2022
1.9 _ Applications of Queue and Reverse
Queue
250
Reversing Queue
• Give an algorithm for reversing a queue Q.
Only following standard operations are
allowed on queue.
– enqueue(x) : Add an item x to rear of queue.
– dequeue() : Remove an item from front of queue.
– empty() : Checks if a queue is empty or not.
4/6/2022
1.9 _ Applications of Queue and Reverse
Queue
251
Example
4/6/2022
1.9 _ Applications of Queue and Reverse
Queue
252
Reversing Queue using Stack
• For reversing the queue one approach could be to store the
elements of the queue in a temporary data structure in a manner
such that if we re-insert the elements in the queue they would get
inserted in reverse order. So now our task is to choose such data-
structure which can serve the purpose.
• According to the approach, the data-structure should have the
property of ‘LIFO’ as the last element to be inserted in the data
structure should actually be the first element of the reversed
queue.
• The stack could help in approaching this problem.
• This will be a two-step process:
– Pop the elements from the queue and insert into the stack. (Topmost
element of the stack is the last element of the queue)
– Pop the elements of the stack to insert back into the queue. (The last
element is the first one to be inserted into the queue)
4/6/2022
1.9 _ Applications of Queue and Reverse
Queue
253
Thank you
4/6/2022
1.9 _ Applications of Queue and Reverse
Queue
254

More Related Content

What's hot

Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queuePpt on Linked list,stack,queue
Ppt on Linked list,stack,queueSrajan Shukla
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURESbca2010
 
Polynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptxPolynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptxAlbin562191
 
12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMSkoolkampus
 
Introduction to data structure
Introduction to data structure Introduction to data structure
Introduction to data structure NUPOORAWSARMOL
 
UNIT I LINEAR DATA STRUCTURES – LIST
UNIT I 	LINEAR DATA STRUCTURES – LIST 	UNIT I 	LINEAR DATA STRUCTURES – LIST
UNIT I LINEAR DATA STRUCTURES – LIST Kathirvel Ayyaswamy
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structurekalyanineve
 
Data Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptxData Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptxEllenGrace9
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data StructureDharita Chokshi
 
Data Structures and Algorithm Analysis
Data Structures  and  Algorithm AnalysisData Structures  and  Algorithm Analysis
Data Structures and Algorithm AnalysisMary Margarat
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data StructureMeghaj Mallick
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structureZaid Shabbir
 

What's hot (20)

Linked List
Linked ListLinked List
Linked List
 
Data structure and its types.
Data structure and its types.Data structure and its types.
Data structure and its types.
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queuePpt on Linked list,stack,queue
Ppt on Linked list,stack,queue
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
 
Polynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptxPolynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptx
 
12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Introduction to data structure
Introduction to data structure Introduction to data structure
Introduction to data structure
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
 
UNIT I LINEAR DATA STRUCTURES – LIST
UNIT I 	LINEAR DATA STRUCTURES – LIST 	UNIT I 	LINEAR DATA STRUCTURES – LIST
UNIT I LINEAR DATA STRUCTURES – LIST
 
Queue
QueueQueue
Queue
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
 
Data Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptxData Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptx
 
Linked list
Linked listLinked list
Linked list
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Data Structures and Algorithm Analysis
Data Structures  and  Algorithm AnalysisData Structures  and  Algorithm Analysis
Data Structures and Algorithm Analysis
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 
Linked list
Linked listLinked list
Linked list
 
Tree and graph
Tree and graphTree and graph
Tree and graph
 

Similar to Linear Data Structures - List, Stack and Queue

Introduction to Data Structures and Linked List
Introduction to Data Structures and Linked ListIntroduction to Data Structures and Linked List
Introduction to Data Structures and Linked ListSelvaraj Seerangan
 
Data Structures and Algorithms - Lec 05.pptx
Data Structures and Algorithms - Lec 05.pptxData Structures and Algorithms - Lec 05.pptx
Data Structures and Algorithms - Lec 05.pptxRameshaFernando2
 
LINKED LIST.pptx
LINKED LIST.pptxLINKED LIST.pptx
LINKED LIST.pptxDr.Shweta
 
DATA STRUCTURES AND LINKED LISTS IN C.pptx
DATA STRUCTURES AND LINKED LISTS IN C.pptxDATA STRUCTURES AND LINKED LISTS IN C.pptx
DATA STRUCTURES AND LINKED LISTS IN C.pptxSKUP1
 
DATA STRUCTURES AND LINKED LISTS IN C.pptx
DATA STRUCTURES AND LINKED LISTS IN C.pptxDATA STRUCTURES AND LINKED LISTS IN C.pptx
DATA STRUCTURES AND LINKED LISTS IN C.pptxLECO9
 
Unit 1 linked list
Unit 1 linked listUnit 1 linked list
Unit 1 linked listLavanyaJ28
 
Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm KristinaBorooah
 
ds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdfds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdfKamranAli649587
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure shameen khan
 
mbit_Unit-2_Linked List.pptx
mbit_Unit-2_Linked List.pptxmbit_Unit-2_Linked List.pptx
mbit_Unit-2_Linked List.pptxjotaro11
 
data structures and applications power p
data structures and applications power pdata structures and applications power p
data structures and applications power pMeghaKulkarni27
 
Different types of Linked list.
Different types of Linked list.Different types of Linked list.
Different types of Linked list.JAYANTAOJHA
 

Similar to Linear Data Structures - List, Stack and Queue (20)

Introduction to Data Structures and Linked List
Introduction to Data Structures and Linked ListIntroduction to Data Structures and Linked List
Introduction to Data Structures and Linked List
 
Data Structures and Algorithms - Lec 05.pptx
Data Structures and Algorithms - Lec 05.pptxData Structures and Algorithms - Lec 05.pptx
Data Structures and Algorithms - Lec 05.pptx
 
LINKED LIST.pptx
LINKED LIST.pptxLINKED LIST.pptx
LINKED LIST.pptx
 
DATA STRUCTURES AND LINKED LISTS IN C.pptx
DATA STRUCTURES AND LINKED LISTS IN C.pptxDATA STRUCTURES AND LINKED LISTS IN C.pptx
DATA STRUCTURES AND LINKED LISTS IN C.pptx
 
DATA STRUCTURES AND LINKED LISTS IN C.pptx
DATA STRUCTURES AND LINKED LISTS IN C.pptxDATA STRUCTURES AND LINKED LISTS IN C.pptx
DATA STRUCTURES AND LINKED LISTS IN C.pptx
 
Linked list
Linked listLinked list
Linked list
 
Unit 1 linked list
Unit 1 linked listUnit 1 linked list
Unit 1 linked list
 
Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm
 
ds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdfds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdf
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
mbit_Unit-2_Linked List.pptx
mbit_Unit-2_Linked List.pptxmbit_Unit-2_Linked List.pptx
mbit_Unit-2_Linked List.pptx
 
Linked list (1).pptx
Linked list (1).pptxLinked list (1).pptx
Linked list (1).pptx
 
lecture 02.2.ppt
lecture 02.2.pptlecture 02.2.ppt
lecture 02.2.ppt
 
Lecture 2b lists
Lecture 2b listsLecture 2b lists
Lecture 2b lists
 
Linked List
Linked ListLinked List
Linked List
 
linked list.pptx
linked list.pptxlinked list.pptx
linked list.pptx
 
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
 
data structures and applications power p
data structures and applications power pdata structures and applications power p
data structures and applications power p
 
Different types of Linked list.
Different types of Linked list.Different types of Linked list.
Different types of Linked list.
 
Data structure day1
Data structure day1Data structure day1
Data structure day1
 

More from Selvaraj Seerangan

Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Selvaraj Seerangan
 
END SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptxEND SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptxSelvaraj Seerangan
 
Design Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptxDesign Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptxSelvaraj Seerangan
 
CAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptxCAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptxSelvaraj Seerangan
 
[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptxSelvaraj Seerangan
 
CAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptxCAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptxSelvaraj Seerangan
 
Design Thinking - Empathize Phase
Design Thinking - Empathize PhaseDesign Thinking - Empathize Phase
Design Thinking - Empathize PhaseSelvaraj Seerangan
 
18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdfSelvaraj Seerangan
 
CAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptxCAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptxSelvaraj Seerangan
 
[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptxSelvaraj Seerangan
 
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdfSelvaraj Seerangan
 

More from Selvaraj Seerangan (20)

Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
 
Unit 5 _ Fog Computing .pdf
Unit 5 _ Fog Computing .pdfUnit 5 _ Fog Computing .pdf
Unit 5 _ Fog Computing .pdf
 
CAT III Answer Key.pdf
CAT III Answer Key.pdfCAT III Answer Key.pdf
CAT III Answer Key.pdf
 
END SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptxEND SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptx
 
Design Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptxDesign Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptx
 
CAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptxCAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptx
 
[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 5 _ Evolve.pptx[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 5 _ Evolve.pptx
 
[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 4 _ Engage.pptx[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 4 _ Engage.pptx
 
[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx
 
CAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptxCAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptx
 
Design Thinking - Empathize Phase
Design Thinking - Empathize PhaseDesign Thinking - Empathize Phase
Design Thinking - Empathize Phase
 
CAT-II Answer Key.pdf
CAT-II Answer Key.pdfCAT-II Answer Key.pdf
CAT-II Answer Key.pdf
 
PSP LAB MANUAL.pdf
PSP LAB MANUAL.pdfPSP LAB MANUAL.pdf
PSP LAB MANUAL.pdf
 
18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf
 
DS LAB MANUAL.pdf
DS LAB MANUAL.pdfDS LAB MANUAL.pdf
DS LAB MANUAL.pdf
 
CAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptxCAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptx
 
[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx
 
CAT-1 Answer Key.doc
CAT-1 Answer Key.docCAT-1 Answer Key.doc
CAT-1 Answer Key.doc
 
Unit 3 Complete.pptx
Unit 3 Complete.pptxUnit 3 Complete.pptx
Unit 3 Complete.pptx
 
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
 

Recently uploaded

Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 

Recently uploaded (20)

Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 

Linear Data Structures - List, Stack and Queue

  • 1. UNIT I : Linear Data Structures and Its Applications By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 2. Syllabus – Unit Wise 4/6/2022 1.1 _ Singly Linked List 2
  • 3. List of Exercises 4/6/2022 1.1 _ Singly Linked List 3
  • 4. Text Book and Reference Book 4/6/2022 1.1 _ Singly Linked List 4
  • 5. 4/6/2022 1.1 _ Singly Linked List 5
  • 6. Unit I : Contents 1. Linked List 2. Doubly Linked List 3. Circular Linked List 4. Applications of List – Polynomial Addition – Representing Sparse matrices 5. Reversing a Linked List 6. Cloning a Linked List 7. Sorting of Linked List 8. Applications of Stack – Towers of Hanoi – Balancing Parenthesis – String Reversal 9. Applications of Queue 10. Reversing the Queue using Stack. 4/6/2022 6 1.1 _ Singly Linked List
  • 7. Classification of Data Structures 4/6/2022 1.1 _ Singly Linked List 7
  • 8. Linear Data Structures • In linear data structure, the elements are accessed in a sequential order. • But it is not compulsory to store all elements sequentially (Say, Linked list). • For Examples, – Array – Queue – Stack – linked list • They can be implemented in memory using two ways. • The first method is by having a linear relationship between elements by means of sequential memory locations. • The second method is by having a linear relationship by using links. 4/6/2022 1.1 _ Singly Linked List 8
  • 9. Non-Linear Data Structures • The non-linear data structure does not organize the data in a sequential manner. • When the data elements are organised in some arbitrary fashion without any sequence, such data structures are called non- linear data structures. • For Example, – Tree – Graph 4/6/2022 1.1 _ Singly Linked List 9
  • 10. Linear and Non-Linear 4/6/2022 1.1 _ Singly Linked List 10
  • 11. Linear and Non-Linear 4/6/2022 1.1 _ Singly Linked List 11
  • 12. Introduction to Linked List • A linked list is a linear data structure, in which the – elements are not stored at contiguous memory locations and – elements are linked using pointers. • Each element (we will call it as a node) of a list is comprising of two items : – data and – reference to the next node. 4/6/2022 1.1 _ Singly Linked List 12
  • 13. Introduction to Linked List • The last node has a reference to null. • The entry point into a linked list is called the Head of the list. • It should be noted that Head is not a separate node, but the reference to the first node. • If the list is empty then the Head is a null reference. 4/6/2022 1.1 _ Singly Linked List 13
  • 14. Introduction to Linked List • A linked list is a dynamic data structure. • The number of nodes in a list is not fixed and can grow and shrink on demand. • Any application which has to deal with an unknown number of objects will need to use a linked list. • A node in linked list contains two types of fields namely Data and Next. • The left part of the node which contains data may include a simple data type, an array, or a structure. • The right part of the node contains a pointer to the next node. • Linked list is also called a self-referential data type, since every node contains a pointer to another node which is of same type. 4/6/2022 1.1 _ Singly Linked List 14
  • 15. Introduction to Linked List • A linked list contains a pointer variable, Head, which stores the address of the first node in the list. • The entire list can be traversed using this Head pointer. • The address of the first node is available in the Head pointer. • The address of its succeeding node will be stored in Next part of the node. • Using this method, the individual nodes of the list form a chain of nodes. • If Head = NULL, means the linked list is empty and contains no nodes. 4/6/2022 1.1 _ Singly Linked List 15
  • 16. Linked List Vs Arrays • Arrays can be used to store linear data of similar types, but arrays have the following limitations. • 1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage. • 2) Inserting a new element in an array of elements is expensive because the room has to be created for the new elements and to create room existing elements have to be shifted. • For example, in a system, if we maintain a sorted list of IDs in an array id[]. id[] = [1000, 1010, 1050, 2000, 2040]. • And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 (excluding 1000). • Deletion is also expensive with arrays until unless some special techniques are used. For example, to delete 1010 in id[], everything after 1010 has to be moved. 4/6/2022 1.1 _ Singly Linked List 16
  • 17. Linked List Vs Arrays • Advantages over arrays – 1) Dynamic size – 2) Ease of insertion/deletion • Drawbacks: – 1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists efficiently with its default implementation. – 2) Extra memory space for a pointer is required with each element of the list. – 3) Not cache friendly. Since array elements are contiguous locations, there is locality of reference which is not there in case of linked lists. 4/6/2022 1.1 _ Singly Linked List 17
  • 18. Linked List Vs Arrays • Both arrays and linked lists are a linear collection of data elements. • But unlike an array, a linked list does not store its nodes in consecutive memory locations. • Another difference between an array and a linked list is that a linked list does not allow random access of data. Nodes in a linked list can be accessed only in a sequential manner. • Another advantage of a linked list over an array is that we can add any number of elements in the list. This is not possible in case of an array. • For example, if we declare an integer array as int sno[10], then the array can store a maximum of 10 data elements and not even one more than that. There is no such restriction in the case of a linked list. • Thus, linked lists provide an efficient way of storing related data and perform basic operations such as insertion, deletion and updation of information at the cost of the extra space required for storing the address of the next node. 4/6/2022 1.1 _ Singly Linked List 18
  • 19. Linked List Vs Arrays 4/6/2022 1.1 _ Singly Linked List 19
  • 20. Linked List Vs Arrays 4/6/2022 1.1 _ Singly Linked List 20
  • 21. Linked List Vs Arrays • Below Figures gives a pictorial representation showing how consecutive memory locations are allocated for array, while in case of linked list random memory locations are assigned to nodes, but each node is connected to its next node using pointer. 4/6/2022 1.1 _ Singly Linked List 21
  • 22. Memory Allocation and Deallocation for a linked list • In linked lists, data is stored in the form of nodes and at runtime memory is allocated for creating nodes using malloc() function. 4/6/2022 1.1 _ Singly Linked List 22
  • 23. Memory Allocation and Deallocation for a linked list 4/6/2022 1.1 _ Singly Linked List 23
  • 24. 4/6/2022 1.1 _ Singly Linked List 24
  • 25. 4/6/2022 1.1 _ Singly Linked List 25
  • 26. 4/6/2022 1.1 _ Singly Linked List 26
  • 27. 4/6/2022 1.1 _ Singly Linked List 27
  • 28. 4/6/2022 1.1 _ Singly Linked List 28 Creating 3 nodes in a linked list and Printing
  • 29. 4/6/2022 1.1 _ Singly Linked List 29
  • 30. Different types of linked lists • There are different types of linked lists available. They are – Singly linked list – Doubly linked list – Circular linked list 4/6/2022 1.1 _ Singly Linked List 30
  • 31. Singly linked list • Singly Linked Lists are a type of data structure in which each node in the list stores the contents and a pointer or reference to the next node in the list. • It does not store any pointer or reference to the previous node. • To store a singly linked list, only the reference or pointer to the first node in that list must be stored. • The last node in a single linked list points to nothing. • A singly linked list can be traversed in only one direction from Head to the last node 4/6/2022 1.1 _ Singly Linked List 31
  • 32. Doubly linked list • A doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence. • A doubly linked list consists of data, a pointer to the next node and a pointer to the previous node. • The First and last node of a linked list contains a terminator generally a NULL value, that determines the start and end of the list. • Doubly linked list is sometimes also referred as bi-directional linked list since it allows traversal of nodes in both direction. • Doubly linked list can be used in navigation systems where both front and back navigation is required. It is used by browsers to implement backward and forward navigation of visited web pages i.e. back and forward button. • It is one of the most efficient data structure to implement when traversing in both direction is required. • Doubly linked list uses extra memory when compared to array and singly linked list. 4/6/2022 1.1 _ Singly Linked List 32
  • 33. Circular linked list • In a circular linked list, the last node contains a pointer to the first node of the list. • It is basically a linear linked list that may be singly or doubly. • In the list every node points to the next node and last node points to the first node, thus forming a circle. • Since it forms a circle, it is called as a circular linked list. 4/6/2022 1.1 _ Singly Linked List 33
  • 34. Operations in Linked List • Creating a List • Traversing a List • Adding a Node • Deleting a Node 4/6/2022 1.1 _ Singly Linked List 34
  • 35. 4/6/2022 1.1 _ Singly Linked List 35 Creating 3 nodes in a linked list and Printing
  • 36. 4/6/2022 1.1 _ Singly Linked List 36
  • 37. Creating n nodes in a linked list and Traversing #include <stdio.h> #include <stdlib.h> /* Structure of a node */ struct node { int data; // Data struct node *next; // Address }*head; void createList(int n); void traverseList(); 4/6/2022 1.1 _ Singly Linked List 37
  • 38. int main() { int n; printf("Enter the total number of nodes: "); scanf("%d", &n); createList(n); printf("nData in the list n"); traverseList(); return 0; } 4/6/2022 1.1 _ Singly Linked List 38
  • 39. /* * Create a list of n nodes */ void createList(int n) { struct node *newNode, *temp; int info, i; head = (struct node *)malloc(sizeof(struct node)); printf("Enter the data of node 1: "); // Input data of node from the user scanf("%d", &info); head->data = info; // Link data field with info head->next = NULL; // Link address field to NULL 4/6/2022 1.1 _ Singly Linked List 39
  • 40. // Create n - 1 nodes and add to list temp = head; // to mention temp is the last node in the list for(i=2; i<=n; i++) { newNode = (struct node *)malloc(sizeof(struct node)); printf("Enter the data of node %d: ", i); scanf("%d", &info); newNode->data = info; // Link data field of newNode newNode->next = NULL; // Make sure new node points to NULL temp->next = newNode; // Link previous node with newNode temp = temp->next; // Make current node as previous node } } 4/6/2022 1.1 _ Singly Linked List 40
  • 41. /* * Display entire list */ void traverseList() { struct node *temp; temp = head; while(temp != NULL) { printf("Data = %dn", temp->data); // Print data of current node temp = temp->next; // Move to next node } } 4/6/2022 1.1 _ Singly Linked List 41
  • 42. Output Enter the total number of nodes: 3 Enter the data of node 1: 23 Enter the data of node 2: 56 Enter the data of node 3: 89 Data in the list Data = 23 Data = 56 Data = 89 4/6/2022 1.1 _ Singly Linked List 42
  • 43. Adding a Node in Linked List • A new node can be added to the already existing linked list. • A node can be added in three different ways. – At the front of the given linked list – At the middle of the given linked list – At the end of the given linked list 4/6/2022 1.1 _ Singly Linked List 43
  • 44. Insert at the front of the given linked list • Consider the linked list shown in the Figure. Suppose we want to add a new node 5 at the beginning of the list. The following steps will be done in the linked list to add the node. 4/6/2022 1.1 _ Singly Linked List 44
  • 45. Step 1 • Step 1: Allocate memory for the new data. 4/6/2022 1.1 _ Singly Linked List 45
  • 46. Step 2 • Step 2: initialize its data value to 5. 4/6/2022 1.1 _ Singly Linked List 46
  • 47. Step 3 • Step 3: Add the newly created node as the first node of the list. Now the Next part of the new node will contain the address of Head. 4/6/2022 1.1 _ Singly Linked List 47
  • 48. Step 4 • Step 4: Now assign Head to point to the new node. Now Head will have the starting address of the linked list. 4/6/2022 1.1 _ Singly Linked List 48
  • 49. 4/6/2022 1.1 _ Singly Linked List 49
  • 50. Insert at the middle of the given linked list • It involves insertion after the specified node of the linked list. We need to skip the desired number of nodes in order to reach the node after which the new node will be inserted. Consider the linked list shown in Figure. Suppose we want to add a new node 25 after the node 20 of the given list. The following steps will be done in the linked list to add the node. 4/6/2022 1.1 _ Singly Linked List 50
  • 51. Step 1 • Step 1: Allocate memory for the new data. 4/6/2022 1.1 _ Singly Linked List 51
  • 52. Step 2 • Step 2: initialize its data value to 25. 4/6/2022 1.1 _ Singly Linked List 52
  • 53. Step 3 • Step 3: Read the element after which you ant to insert. 4/6/2022 1.1 _ Singly Linked List 53
  • 54. Step 4 • Step 4: Assign variable ptr to point to Head node. Move ptr to the next node until the Data part of the ptr points to 20. 4/6/2022 1.1 _ Singly Linked List 54
  • 55. Step 5 • Step 5: Assign the NEXT part of the new node to NEXT part of the ptr. 4/6/2022 1.1 _ Singly Linked List 55
  • 56. Step 6 • Step 6: Assign the NEXT part of the ptr to new node. 4/6/2022 1.1 _ Singly Linked List 56
  • 57. 4/6/2022 1.1 _ Singly Linked List 57
  • 58. 4/6/2022 1.1 _ Singly Linked List 58
  • 59. Insert at the last of the given linked list • It involves insertion at the last of the linked list. The new node can be inserted as the only node in the list or it can be inserted as the last one. Consider the linked list shown in Figure. Suppose we want to add a new node 45 at the last of the given list. The following steps will be done in the linked list to add the node. 4/6/2022 1.1 _ Singly Linked List 59
  • 60. Step 1 • Step 1: Allocate memory for the new data. 4/6/2022 1.1 _ Singly Linked List 60
  • 61. Step 2 • Step 2: initialize its data value to 45. 4/6/2022 1.1 _ Singly Linked List 61
  • 62. Step 3 • Step 3: Assign variable ptr to point to Head node. Move ptr to the next node until the Next part of the ptr points to NULL. 4/6/2022 1.1 _ Singly Linked List 62
  • 63. Step 4 • Step 4: Assign the NEXT part of the new node to NULL. 4/6/2022 1.1 _ Singly Linked List 63
  • 64. Step 5 • Step 5: Assign the NEXT part of the ptr to new node. 4/6/2022 1.1 _ Singly Linked List 64
  • 65. 4/6/2022 1.1 _ Singly Linked List 65
  • 66. 4/6/2022 1.1 _ Singly Linked List 66
  • 67. Time Complexity • Time complexity of insert_begin() is O(1) as it does a constant amount of work. • Time complexity of insert_middle() is O(1) as it does a constant amount of work. • Time complexity of insert_last() is O(n) where n is the number of nodes in linked list. Since there is a loop from head to end, the function does O(n) work. – This method can also be optimized to work in O(1) by keeping an extra pointer to the tail of linked list 4/6/2022 1.1 _ Singly Linked List 67
  • 68. Deleting a Node in Linked List • A new node can be deleted to the already existing linked list. • A node can be deleted in three different ways. – At the front of the given linked list – At the middle of the given linked list – At the end of the given linked list 4/6/2022 1.1 _ Singly Linked List 68
  • 69. 4/6/2022 1.1 _ Singly Linked List 69 Deletion at the front of the given linked list
  • 70. Deletion at the front of the given linked list • It involves deletion of a node from the beginning of the list. Consider the linked list shown in Figure. Suppose we want to delete the node at the beginning of the list. The following steps will be done in the linked list to delete the node. 4/6/2022 1.1 _ Singly Linked List 70
  • 71. Step 1 • Step 1: Assign variable ptr to Head node. 4/6/2022 1.1 _ Singly Linked List 71
  • 72. Step 2 • Step 2: Assign Head to point ptr next. 4/6/2022 1.1 _ Singly Linked List 72
  • 73. Step 3 • Step 3: Deallocate ptr . 4/6/2022 1.1 _ Singly Linked List 73
  • 74. 4/6/2022 1.1 _ Singly Linked List 74
  • 75. 4/6/2022 1.1 _ Singly Linked List 75 Deletion at the middle of the given linked list
  • 76. Deletion at the middle of the given linked list • It involves deletion of a node from the middle of the list. Consider the linked list shown in Figure. Suppose we want to delete the node 20 from the given list. The following steps will be done in the linked list to delete the node. 4/6/2022 1.1 _ Singly Linked List 76
  • 77. 4/6/2022 1.1 _ Singly Linked List 77
  • 78. 4/6/2022 1.1 _ Singly Linked List 78
  • 79. Deletion at the end of the given linked list • It involves deletion of the last node from the list. Consider the linked list shown in Figure. Suppose we want to delete the last node from the given list. The following steps will be done in the linked list to delete the node. 4/6/2022 1.1 _ Singly Linked List 79
  • 80. 4/6/2022 1.1 _ Singly Linked List 80
  • 81. 4/6/2022 1.1 _ Singly Linked List 81
  • 82. Time Complexity • Time complexity of delete_begin() is O(1) as it does a constant amount of work. • Time complexity of delete_middle() is O(n) as it does a constant amount of work. • Time complexity of delete_last() is O(n) where n is the number of nodes in linked list. Since there is a loop from head to end, the function does O(n) work. 4/6/2022 1.1 _ Singly Linked List 82
  • 83. Thank you 4/6/2022 1.1 _ Singly Linked List 83
  • 84. 1.2 Doubly Linked List By Mr.S.Selvaraj, AP(SRG)/CSE KEC
  • 85. Doubly linked lists 🞑 A doubly linked list is a list that can be traversed both from left to right and from right to left first last 🞑 It requires to store two head pointers: 🞑 The first one points to the first element in the list 🞑 The second one points to the last element in the list
  • 86. Linked lists vs. Doubly linked lists 🞑 Linked lists 🞑 Simple implementation 🞑 Require less memory 🞑 Doubly linked lists 🞑 More complex implementation 🞑 Require more memory 🞑 Accessing elements is easier, since accessing from the “head” (i.e., leftmost element) costs as much as accessing from the “tail” (i.e., rightmost element) 🞑 Worst case: accessing the middle element (it requires to go through half list, both from left and from right)
  • 87. Creating and printing doubly linked lists
  • 88. Node definition 🞑 Each node contains: 🞑 The data 🞑 A pointer to the previous element (left-side) 🞑 A pointer to the next element (right-side) previousPtr data nextPtr
  • 89. Creating a doubly linked list 🞑 We are going to create a doubly linked list by hand: first second last
  • 90. second last Creating a doubly linked list 🞑 We are going to create a doubly linked list by hand: first
  • 91. second last Creating a doubly linked list 🞑 We are going to create a doubly linked list by hand: first
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 111. 1.3 Circular Linked List By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 112. Circular linked list • Circular linked list is a linked list where all nodes are connected to form a circle. • There is no NULL at the end. • A circular linked list can be a singly circular linked list or doubly circular linked list. 4/6/2022 112 1.3 _ Circular Linked List
  • 113. Circular linked list 4/6/2022 113 1.3 _ Circular Linked List
  • 114. Circular linked list • In a circular linked list, the last node contains a pointer to the first node of the list. • It is basically a linear linked list that may be singly or doubly. • In the list every node points to the next node and last node points to the first node, thus forming a circle. • Since it forms a circle, it is called as a circular linked list. 4/6/2022 1.3 _ Circular Linked List 114
  • 115. 1. Any node can be a starting point. – We can traverse the whole list by starting from any point. – We just need to stop when the first visited node is visited again. Advantages of Circular linked list 4/6/2022 115 1.3 _ Circular Linked List
  • 116. Advantages of Circular linked list 2. Useful for implementation of queue. – Unlike this implementation, we don’t need to maintain two pointers for front and rear if we use circular linked list. – We can maintain a pointer to the last inserted node and front can always be obtained as next of last. 4/6/2022 116 1.3 _ Circular Linked List
  • 117. Advantages of Circular linked list 3. Circular lists are useful in applications to repeatedly go around the list. – For example, when multiple applications are running on a PC. – It is common for the operating system to put the running applications on a list and then to cycle through them, giving each of them a slice of time to execute, and then making them wait while the CPU is given to another application. – It is convenient for the operating system to use a circular list so that when it reaches the end of the list it can cycle around to the front of the list. 4/6/2022 117 1.3 _ Circular Linked List
  • 118. Advantages of Circular linked list 4. Circular Doubly Linked Lists are used for implementation of advanced data structures like Fibonacci Heap 4/6/2022 118 1.3 _ Circular Linked List
  • 119. Adding a node • Insertion at the beginning: Inserting a new node as the first node. The next pointer of last will point to this node and this new node will point to the previous first node. 4/6/2022 1.3 _ Circular Linked List 119
  • 120. Operations in Circular Linked List • Creating a List • Traversing a List • Adding a Node • Deleting a Node 4/6/2022 1.3 _ Circular Linked List 120
  • 121. 4/6/2022 1.3 _ Circular Linked List 121 Creating 3 nodes in a linked list and Printing
  • 122. 4/6/2022 1.3 _ Circular Linked List 122
  • 123. Creating n nodes in a linked list and Traversing #include <stdio.h> #include <stdlib.h> /* Structure of a node */ struct node { int data; // Data struct node *next; // Address }*head; void createList(int n); void traverseList(); 4/6/2022 1.3 _ Circular Linked List 123
  • 124. int main() { int n; printf("Enter the total number of nodes: "); scanf("%d", &n); createList(n); printf("nData in the list n"); traverseList(); return 0; } 4/6/2022 1.3 _ Circular Linked List 124
  • 125. /* * Create a list of n nodes */ void createList(int n) { struct node *newNode, *temp; int info, i; head = (struct node *)malloc(sizeof(struct node)); printf("Enter the data of node 1: "); // Input data of node from the user scanf("%d", &info); head->data = info; // Link data field with info head->next = NULL; // Link address field to NULL 4/6/2022 1.3 _ Circular Linked List 125
  • 126. // Create n - 1 nodes and add to list temp = head; // to mention temp is the last node in the list for(i=2; i<=n; i++) { newNode = (struct node *)malloc(sizeof(struct node)); printf("Enter the data of node %d: ", i); scanf("%d", &info); newNode->data = info; // Link data field of newNode newNode->next = NULL; // Make sure new node points to NULL temp->next = newNode; // Link previous node with newNode temp = temp->next; // Make current node as previous node } } 4/6/2022 1.3 _ Circular Linked List 126
  • 127. /* * Display entire list */ void traverseList() { struct node *temp; temp = head; while(temp != NULL) { printf("Data = %dn", temp->data); // Print data of current node temp = temp->next; // Move to next node } } 4/6/2022 1.3 _ Circular Linked List 127
  • 128. Output Enter the total number of nodes: 3 Enter the data of node 1: 23 Enter the data of node 2: 56 Enter the data of node 3: 89 Data in the list Data = 23 Data = 56 Data = 89 4/6/2022 1.3 _ Circular Linked List 128
  • 129. Adding a Node in Linked List • A new node can be added to the already existing linked list. • A node can be added in three different ways. – At the front of the given linked list – At the middle of the given linked list – At the end of the given linked list 4/6/2022 1.3 _ Circular Linked List 129
  • 130. Insert at the front of the given linked list • Consider the linked list shown in the Figure. Suppose we want to add a new node 5 at the beginning of the list. The following steps will be done in the linked list to add the node. 4/6/2022 1.3 _ Circular Linked List 130
  • 131. Step 1 • Step 1: Allocate memory for the new data. 4/6/2022 1.3 _ Circular Linked List 131
  • 132. Step 2 • Step 2: initialize its data value to 5. 4/6/2022 1.3 _ Circular Linked List 132
  • 133. Step 3 • Step 3: Add the newly created node as the first node of the list. Now the Next part of the new node will contain the address of Head. 4/6/2022 1.3 _ Circular Linked List 133
  • 134. Step 4 • Step 4: Now assign Head to point to the new node. Now Head will have the starting address of the linked list. 4/6/2022 1.3 _ Circular Linked List 134
  • 135. 4/6/2022 1.3 _ Circular Linked List 135
  • 136. Insert at the middle of the given linked list • It involves insertion after the specified node of the linked list. We need to skip the desired number of nodes in order to reach the node after which the new node will be inserted. Consider the linked list shown in Figure. Suppose we want to add a new node 25 after the node 20 of the given list. The following steps will be done in the linked list to add the node. 4/6/2022 1.3 _ Circular Linked List 136
  • 137. Step 1 • Step 1: Allocate memory for the new data. 4/6/2022 1.3 _ Circular Linked List 137
  • 138. Step 2 • Step 2: initialize its data value to 25. 4/6/2022 1.3 _ Circular Linked List 138
  • 139. Step 3 • Step 3: Read the element after which you ant to insert. 4/6/2022 1.3 _ Circular Linked List 139
  • 140. Step 4 • Step 4: Assign variable ptr to point to Head node. Move ptr to the next node until the Data part of the ptr points to 20. 4/6/2022 1.3 _ Circular Linked List 140
  • 141. Step 5 • Step 5: Assign the NEXT part of the new node to NEXT part of the ptr. 4/6/2022 1.3 _ Circular Linked List 141
  • 142. Step 6 • Step 6: Assign the NEXT part of the ptr to new node. 4/6/2022 1.3 _ Circular Linked List 142
  • 143. 4/6/2022 1.3 _ Circular Linked List 143
  • 144. 4/6/2022 1.3 _ Circular Linked List 144
  • 145. Insert at the last of the given linked list • It involves insertion at the last of the linked list. The new node can be inserted as the only node in the list or it can be inserted as the last one. Consider the linked list shown in Figure. Suppose we want to add a new node 45 at the last of the given list. The following steps will be done in the linked list to add the node. 4/6/2022 1.3 _ Circular Linked List 145
  • 146. Step 1 • Step 1: Allocate memory for the new data. 4/6/2022 1.3 _ Circular Linked List 146
  • 147. Step 2 • Step 2: initialize its data value to 45. 4/6/2022 1.3 _ Circular Linked List 147
  • 148. Step 3 • Step 3: Assign variable ptr to point to Head node. Move ptr to the next node until the Next part of the ptr points to NULL. 4/6/2022 1.3 _ Circular Linked List 148
  • 149. Step 4 • Step 4: Assign the NEXT part of the new node to NULL. 4/6/2022 1.3 _ Circular Linked List 149
  • 150. Step 5 • Step 5: Assign the NEXT part of the ptr to new node. 4/6/2022 1.3 _ Circular Linked List 150
  • 151. 4/6/2022 1.3 _ Circular Linked List 151
  • 152. 4/6/2022 1.3 _ Circular Linked List 152
  • 153. Time Complexity • Time complexity of insert_begin() is O(1) as it does a constant amount of work. • Time complexity of insert_middle() is O(1) as it does a constant amount of work. • Time complexity of insert_last() is O(n) where n is the number of nodes in linked list. Since there is a loop from head to end, the function does O(n) work. – This method can also be optimized to work in O(1) by keeping an extra pointer to the tail of linked list 4/6/2022 1.3 _ Circular Linked List 153
  • 154. Deleting a Node in Linked List • A new node can be deleted to the already existing linked list. • A node can be deleted in three different ways. – At the front of the given linked list – At the middle of the given linked list – At the end of the given linked list 4/6/2022 1.3 _ Circular Linked List 154
  • 155. 4/6/2022 1.3 _ Circular Linked List 155 Deletion at the front of the given linked list
  • 156. 1.4 Applications of Linked List By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 157. Unit I : Contents 1. Linked List 2. Doubly Linked List 3. Circular Linked List 4. Applications of List – Polynomial Addition – Representing Sparse matrices 5. Reversing a Linked List 6. Cloning a Linked List 7. Sorting of Linked List 8. Applications of Stack – Towers of Hanoi – Balancing Parenthesis – String Reversal 9. Applications of Queue 10. Reversing the Queue using Stack. 4/6/2022 157 1.4 _ Applications of Linked List
  • 158. Applications of linked list in computer science • Implementation of stacks and queues. • Implementation of graphs. – Adjacency list representation of graphs is most popular which is uses linked list to store adjacent vertices. • Dynamic memory allocation. – We use linked list of free blocks. • Maintaining directory of names • Performing arithmetic operations on long integers • Manipulation of polynomials by storing constants in the node of linked list • Representing sparse matrices. 4/6/2022 1.4 _ Applications of Linked List 158
  • 159. Applications of linked list in real world • Image viewer – Previous and next images are linked, hence can be accessed by next and previous button. • Previous and next page in web browser – We can access previous and next URL searched in web browser by pressing back and next button since, they are linked as linked list. • Music Player – Songs in music player are linked to previous and next song. you can play songs either from starting or ending of the list. 4/6/2022 1.4 _ Applications of Linked List 159
  • 160. Polynomial Addition Using Linked List • Polynomials and Sparse Matrix are two important applications of arrays and linked lists. • A polynomial is composed of different terms where each of them holds a coefficient and an exponent. • In mathematics, a polynomial is an expression consisting of variables (also called indeterminates) and coefficients. • It involves only the operations of addition, subtraction, multiplication, and non-negative integer exponentiation of variables. • An example of a polynomial of a single indeterminate x is x2 − 4x + 7. • An example in three variables is x3 + 2xyz2 − yz + 1. 4/6/2022 1.4 _ Applications of Linked List 160
  • 161. What is Polynomial? • A polynomial p(x) is the expression in variable x which is in the form (axn + bxn-1 + …. + jx+ k). – where a, b, c …., k fall in the category of real numbers and – 'n' is non negative integer, which is called the degree of polynomial. 4/6/2022 1.4 _ Applications of Linked List 161
  • 162. characteristic of the polynomial • An essential characteristic of the polynomial is that each term in the polynomial expression consists of two parts: – one is the coefficient – other is the exponent • Example : – 10x2 + 26x – Here 10 and 26 are coefficients and – 2, 1 is its exponential value. 4/6/2022 1.4 _ Applications of Linked List 162
  • 163. Points to keep in mind while working with Polynomials • The sign of each coefficient and exponent is stored within the coefficient and the exponent itself. • Additional terms having equal exponent is possible one. • The storage allocation for each term in the polynomial must be done in ascending and descending order of their exponent. 4/6/2022 1.4 _ Applications of Linked List 163
  • 164. Representing Polynomial Equation in Linked List 4/6/2022 1.4 _ Applications of Linked List 164
  • 165. Polynomial Addition 4/6/2022 1.4 _ Applications of Linked List 165
  • 166. Polynomial Node Structure 4/6/2022 1.4 _ Applications of Linked List 166
  • 167. Sparse Matrix • A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values. If most of the elements of the matrix have 0 value, then it is called a sparse matrix. • Why to use Sparse Matrix instead of simple matrix ? – Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only those elements. – Computing time: Computing time can be saved by logically designing a data structure traversing only non-zero elements. 4/6/2022 1.4 _ Applications of Linked List 167
  • 168. Sparse Matrix 4/6/2022 1.4 _ Applications of Linked List 168
  • 169. Thank you 4/6/2022 1.4 _ Applications of Linked List 169
  • 170. 1.5 Reversing a Linked List By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 171. Unit I : Contents 1. Linked List 2. Doubly Linked List 3. Circular Linked List 4. Applications of List – Polynomial Addition – Representing Sparse matrices 5. Reversing a Linked List 6. Cloning a Linked List 7. Sorting of Linked List 8. Applications of Stack – Towers of Hanoi – Balancing Parenthesis – String Reversal 9. Applications of Queue 10. Reversing the Queue using Stack. 4/6/2022 171 1.4 _ Applications of Linked List
  • 172. Reversing a list 4/6/2022 1.4 _ Applications of Linked List 172
  • 173. Reversing a list • Using array method • Using recursive method • Using iterative method 4/6/2022 1.4 _ Applications of Linked List 173
  • 174. Using array method 4/6/2022 1.4 _ Applications of Linked List 174
  • 175. Using array method 4/6/2022 1.4 _ Applications of Linked List 175
  • 176. Using array method 4/6/2022 1.4 _ Applications of Linked List 176
  • 177. Using array method 4/6/2022 1.4 _ Applications of Linked List 177
  • 178. Recursive Function 4/6/2022 1.4 _ Applications of Linked List 178
  • 179. Structure of recursive function 4/6/2022 1.4 _ Applications of Linked List 179
  • 180. Structure of recursive function 4/6/2022 1.4 _ Applications of Linked List 180
  • 181. Execution of Factorial Function 4/6/2022 1.4 _ Applications of Linked List 181
  • 182. Execution of Factorial Function 4/6/2022 1.4 _ Applications of Linked List 182
  • 183. Execution of Factorial Function 4/6/2022 1.4 _ Applications of Linked List 183
  • 184. Recursive Function Examples 4/6/2022 1.4 _ Applications of Linked List 184
  • 185. Using Recursive Method void reverse(struct node *ptr1); // Function Prototype int main() { createList(n); printf("nData in the list n"); traverseList(); reverse(head); // Function call or initial recursive call return 0; } void reverse(struct node *ptr1) // Function definition { if(ptr1==NULL) // Base case { return; } else { reverse(ptr1->next); // Progressive case printf("%dn",ptr1->data); } } 4/6/2022 1.4 _ Applications of Linked List 185
  • 186. Using iterative method • Given pointer to the head node of a linked list, the task is to reverse the linked list. • We need to reverse the list by changing the links between nodes. • Step 1:Initialize three pointers – prev as NULL, – curr as head and – next as NULL. • Step 2: Iterate through the linked list. In loop, do following. // Before changing next of current, // store next node next = curr->next // Now change next of current // This is where actual reversing happens curr->next = prev // Move prev and curr one step forward prev = curr curr = next 4/6/2022 1.4 _ Applications of Linked List 186
  • 187. Using iterative method 4/6/2022 1.4 _ Applications of Linked List 187
  • 188. Using iterative method static void reverse(struct Node** head_ref) { struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next = NULL; while (current != NULL) { // Store next next = current->next; // Reverse current node's pointer current->next = prev; // Move pointers one position ahead. prev = current; current = next; } *head_ref = prev; } 4/6/2022 1.4 _ Applications of Linked List 188
  • 189. Thank you 4/6/2022 1.4 _ Applications of Linked List 189
  • 190. 1.6 Cloning / Copying a Linked List By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 191. Unit I : Contents 1. Linked List 2. Doubly Linked List 3. Circular Linked List 4. Applications of List – Polynomial Addition – Representing Sparse matrices 5. Reversing a Linked List 6. Cloning/Copying a Linked List 7. Sorting of Linked List 8. Applications of Stack – Towers of Hanoi – Balancing Parenthesis – String Reversal 9. Applications of Queue 10. Reversing the Queue using Stack. 4/6/2022 191 1.4 _ Clone / Copy a Linked List
  • 192. Cloning / Copying a linked list 4/6/2022 1.4 _ Clone / Copy a Linked List 192
  • 193. 4/6/2022 1.4 _ Clone / Copy a Linked List 193
  • 194. 4/6/2022 1.4 _ Clone / Copy a Linked List 194
  • 195. 4/6/2022 1.4 _ Clone / Copy a Linked List 195
  • 196. 4/6/2022 1.4 _ Clone / Copy a Linked List 196
  • 197. 4/6/2022 1.4 _ Clone / Copy a Linked List 197
  • 198. Thank you 4/6/2022 1.4 _ Clone / Copy a Linked List 198
  • 199. 1.7 Searching and Sorting a Linked List By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 200. Unit I : Contents 1. Linked List 2. Doubly Linked List 3. Circular Linked List 4. Applications of List – Polynomial Addition – Representing Sparse matrices 5. Reversing a Linked List 6. Cloning a Linked List 7. Searching and Sorting of Linked List 8. Applications of Stack – Towers of Hanoi – Balancing Parenthesis – String Reversal 9. Applications of Queue 10. Reversing the Queue using Stack. 4/6/2022 200 1.4 _ Searching and Sorting of Linked List
  • 201. Searching a List • Searching is performed in order 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. 4/6/2022 1.4 _ Searching and Sorting of Linked List 201
  • 202. Types of Search • Linear Search • Binary Search 4/6/2022 1.4 _ Searching and Sorting of Linked List 202
  • 203. Linear Search • Linear search is the simplest search algorithm and often called sequential search. • In this type of searching, we simply traverse the list completely and match each element of the list with the item whose location is to be found. • If the match found then location of the item is returned otherwise the algorithm return NULL. • Linear search is mostly used to search an unordered list in which the items are not sorted. 4/6/2022 1.4 _ Searching and Sorting of Linked List 203
  • 204. Linear Search 4/6/2022 1.4 _ Searching and Sorting of Linked List 204
  • 205. void search() { struct node *temp1; int value,flag,i=0; temp1=head; printf("Enter the value you want to search:"); scanf("%d",&value); while(temp1 !=NULL) { if(temp1->data==value) { printf("Yes %d is present at location %d",value,i+1); flag=0; } else { flag=1; } i++; temp1=temp1->next; } if(flag!=0) { printf("No %d is not present",value); } } 4/6/2022 1.4 _ Searching and Sorting of Linked List 205 Search an element in a linked list
  • 206. Binary Search • Binary search is the search technique which works efficiently on the sorted lists. • Hence, in order to search an element into some list by using binary search technique, we must ensure that the list is sorted. • Binary search follows divide and conquer approach in which, the list is divided into two halves and the item is compared with the middle element of the list. • If the match is found then, the location of middle element is returned otherwise, we search into either of the halves depending upon the result produced through the match. 4/6/2022 1.4 _ Searching and Sorting of Linked List 206
  • 207. 4/6/2022 1.4 _ Searching and Sorting of Linked List 207
  • 208. Binary Search 4/6/2022 1.4 _ Searching and Sorting of Linked List 208
  • 209. Sorting a List 4/6/2022 1.4 _ Searching and Sorting of Linked List 209
  • 210. Sorting a List • Many sorting algorithms available: – Bubble sort – Insertion sort – Merge sort – Quick sort – Etc.. 4/6/2022 1.4 _ Searching and Sorting of Linked List 210
  • 211. Sorting a List – using bubble sort • To accomplish this task, we maintain two pointers: ptr1 and ptr2. • Initially, – ptr1 point to head node and – ptr2 will point to node next to ptr1. • Traverse through the list till ptr1 points to null, by comparing ptr1's data with ptr2's data. • If ptr1's data is greater than the ptr2's data, then swap data between them. • In the above example, – ptr1 will initially point to 9 and ptr2 will point to 7. – Since, 9 is greater than 7, swap the data. • Continue this process until the entire list is sorted in ascending order 4/6/2022 1.4 _ Searching and Sorting of Linked List 211
  • 212. void bubblesort() { struct node *ptr1,*ptr2; int temp; ptr1 = head; while (ptr1!=NULL) { ptr2=ptr1->next; while(ptr2!= NULL) { if (ptr1->data > ptr2->data) { temp = ptr1->data; ptr1->data=ptr2->data; ptr2->data=temp; } ptr2 = ptr2->next; } ptr1 = ptr1->next; } } 4/6/2022 1.4 _ Searching and Sorting of Linked List 212 Sorting a List – using bubble sort
  • 213. Thank you 4/6/2022 1.4 _ Searching and Sorting of Linked List 213
  • 214. 1.8 Applications of Stack By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 215. Unit I : Contents 1. Linked List 2. Doubly Linked List 3. Circular Linked List 4. Applications of List – Polynomial Addition – Representing Sparse matrices 5. Reversing a Linked List 6. Cloning a Linked List 7. Sorting of Linked List 8. Applications of Stack – Towers of Hanoi – Balancing Parenthesis – String Reversal 9. Applications of Queue 10. Reversing the Queue using Stack. 4/6/2022 215 1.8 _ Applications of Stack
  • 216. Applications of Stack • Balancing of symbols • Infix to Postfix /Prefix conversion • Redo-undo features at many places like editors, photoshop. • Forward and backward feature in web browsers • Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram problem. • Backtracking is one of the algorithm designing technique .Some example of back tracking are Knight-Tour problem, N-Queen problem, find your way through maze and game like chess or checkers in all this problems we dive into someway if that way is not efficient we come back to the previous state and go into some another path. To get back from current state we need to store the previous state for that purpose we need stack. • In Graph Algorithms like Topological Sorting and Strongly Connected Components • In Memory management any modern computer uses stack as the primary- management for a running purpose. Each program that is running in a computer system has its own memory allocations • String reversal is also a another application of stack. Here one by one each character get inserted into the stack. So the first character of string is on the bottom of the stack and the last element of string is on the top of stack. After Performing the pop operations on stack we get string in reverse order . 4/6/2022 1.8 _ Applications of Stack 216
  • 217. Some Applications in this unit • Applications of Stack – Infix to Postfix / Prefix Conversion – Towers of Hanoi – Balancing Parenthesis – String Reversal 4/6/2022 1.8 _ Applications of Stack 217
  • 218. Infix, Prefix, Postfix Expression • Infix expression: – An expression is called the Infix expression if the operator appears in between the operands in the expression. – Simply of the form (operand1 operator operand2). – Operators are written in-between their operands. X + Y A * ( B + C ) / D • Prefix expression (also known as "Polish notation"): – An expression is called the Prefix expression if the operator appears before the operands in the expression. – Simply of the form (operator operand1 operand2). – Operators are written before their operands. + X Y / * A + B C D 4/6/2022 218 1.8 _ Applications of Stack
  • 219. Infix, Prefix, Postfix Expression • Postfix expression (also known as "Reverse Polish notation"): – An expression is called the postfix expression if the operator appears in the expression after the operands. – Simply of the form (operand1 operand2 operator). – Operators are written after their operands. X Y + A B C + * D / 4/6/2022 219 1.8 _ Applications of Stack
  • 220. Infix, Prefix, Postfix Expression 4/6/2022 220 1.8 _ Applications of Stack
  • 221. Infix to Postfix Conversion Algorithm 1. Scan the infix expression from left to right. 2. If the scanned character is an operand, output it. 3. Else, …..3.1 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. …..3.2 Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in 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 all the operators until a ‘(‘ is encountered, and discard both the parenthesis. 6. Repeat steps 2-6 until infix expression is scanned. 7. Print the output 8. Pop and output from the stack until it is not empty. 4/6/2022 221 1.8 _ Applications of Stack
  • 222. An illustration • First, the symbol a is read, so it is passed through to the output. Then '+' is read and pushed onto the stack. • Next b is read and passed through to the output • Next a '*' is read. The top entry on the operator stack has lower precedence than '*', so nothing is output and '*' is put on the stack. • Next, c is read and output. 4/6/2022 222 1.8 _ Applications of Stack
  • 223. An illustration • The next symbol is a '+'. Checking the stack, we find that we will pop a '*' and place it on the output, pop the other '+', which is not of lower but equal priority, on the stack, and then push the '+'. • The next symbol read is an '(', which, being of highest precedence, is placed on the stack. Then d is read and output. 4/6/2022 223 1.8 _ Applications of Stack
  • 224. An illustration • We continue by reading a '*'. Since open parentheses do not get removed except when a closed parenthesis is being processed, there is no output. Next, e is read and output. • The next symbol read is a '+'. We pop and output '*' and then push '+'. Then we read and output 4/6/2022 224 1.8 _ Applications of Stack
  • 225. An illustration • Now we read a ')', so the stack is emptied back to the '('. We output a '+'. • We read a '*' next; it is pushed onto the stack. Then g is read and output. 4/6/2022 225 1.8 _ Applications of Stack
  • 226. An illustration • The input is now empty, so we pop and output symbols from the stack until it is empty. 4/6/2022 226 1.8 _ Applications of Stack
  • 227. 4/6/2022 227 1.8 _ Applications of Stack
  • 228. 4/6/2022 228 1.8 _ Applications of Stack
  • 229. 4/6/2022 229 1.8 _ Applications of Stack
  • 230. PROBLEM 1. 3+4*5/6 2. (300+23)*(43-21)/(84+7) 3. (4+8)*(6-5)/((3-2)*(2+2)) 4/6/2022 230 1.8 _ Applications of Stack
  • 231. ANSWER 1. 3 4 5 * 6 / + 2. 300 23 + 43 21 -* 84 7 + / 3. 4 8 + 6 5 -* 3 2 –2 2 + * / 4/6/2022 231 1.8 _ Applications of Stack
  • 232. Problems 1) Infix : (A+B) * (C-D) Infix to Postfix : AB+CD-* 2) Infix : A-(B/C)*(A/K)-L Infix to Postfix : ABC/-AK/L-* 4/6/2022 232 1.8 _ Applications of Stack
  • 233. Expression Evaluation The simple algorithm uses a stack and is as follows: 1. Make an empty stack. 2. Read an input string. 3. Read characters one by one until end of string is encountered. 4. If the character is a digit, convert it into an integer and push onto the stack. 5. If the character is not a digit, pop two numbers from the stack and perform the corresponding operation and push the result onto the stack. 6. At end of the string, pop the result from the stack 4/6/2022 233 1.8 _ Applications of Stack
  • 234. ILLUSTRATION 4/6/2022 Next '+' is read, so 3 and 2 are popped from the stack and their sum, 5, is pushed. Next 8 is pushed. 234 1.8 _ Applications of Stack
  • 235. 4/6/2022 Now '*' is read, so 8 and 5 are popped as 8 * 5 = 40 is pushed. 235 1.8 _ Applications of Stack
  • 236. 4/6/2022 236 1.8 _ Applications of Stack
  • 237. PROBLEM 1. 3+4*5/6 2. (300+23)*(43-21)/(84+7) 3. (4+8)*(6-5)/((3-2)*(2+2)) 4/6/2022 237 1.8 _ Applications of Stack
  • 238. Tower of Hanoi • The tower of Hanoi is a mathematical puzzle. • It consists of three rods and a number of disks of different sizes which can slide onto any rod. • The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top. • We have to obtain the same stack on the third rod. • The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules− – Only one disk can be moved at a time. – Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. – No disk may be placed on top of a smaller disk. 4/6/2022 1.8 _ Applications of Stack 238
  • 239. Example - TOH 4/6/2022 1.8 _ Applications of Stack 239
  • 240. Basic Steps and Algorithm for TOH 4/6/2022 1.8 _ Applications of Stack 240
  • 241. Recursive Program for Tower of Hanoi 4/6/2022 1.8 _ Applications of Stack 241
  • 242. Balancing Parenthesis • Given an expression string exp, write a program to examine whether the pairs and the orders of – “{“, “}”, – “(“, “)”, – “[“, “]” are correct in exp. 4/6/2022 1.8 _ Applications of Stack 242
  • 243. Example 4/6/2022 1.8 _ Applications of Stack 243
  • 244. Algorithm • Declare a character stack S. • Now traverse the expression string exp. – If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack. – If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced. • After complete traversal, if there is some starting bracket left in stack then “not balanced” 4/6/2022 1.8 _ Applications of Stack 244
  • 245. 4/6/2022 1.8 _ Applications of Stack 245
  • 246. String Reverse • Given a string, reverse it using stack. For example “KONGU” should be converted to “UGNOK”. • Following is simple algorithm to reverse a string using stack. – Create an empty stack. – One by one push all characters of string to stack. – One by one pop all characters from stack and put them back to string. 4/6/2022 1.8 _ Applications of Stack 246
  • 247. Thank you 4/6/2022 1.8 _ Applications of Stack 247
  • 248. 1.8 Applications of Queue and Reverse the Queue using Stack By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 249. Unit I : Contents 1. Linked List 2. Doubly Linked List 3. Circular Linked List 4. Applications of List – Polynomial Addition – Representing Sparse matrices 5. Reversing a Linked List 6. Cloning a Linked List 7. Sorting of Linked List 8. Applications of Stack – Towers of Hanoi – Balancing Parenthesis – String Reversal 9. Applications of Queue 10. Reversing the Queue using Stack. 4/6/2022 249 1.9 _ Applications of Queue and Reverse Queue
  • 250. 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. • 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. 3) In Operating systems: a) Semaphores b) FCFS ( first come first serve) scheduling, example: FIFO queue c) Spooling in printers d) Buffer for devices like keyboard 4) In Networks: a) Queues in routers/ switches b) Mail Queues 5) Variations: (Deque, Priority Queue, Doubly Ended Priority Queue ) 4/6/2022 1.9 _ Applications of Queue and Reverse Queue 250
  • 251. Reversing Queue • Give an algorithm for reversing a queue Q. Only following standard operations are allowed on queue. – enqueue(x) : Add an item x to rear of queue. – dequeue() : Remove an item from front of queue. – empty() : Checks if a queue is empty or not. 4/6/2022 1.9 _ Applications of Queue and Reverse Queue 251
  • 252. Example 4/6/2022 1.9 _ Applications of Queue and Reverse Queue 252
  • 253. Reversing Queue using Stack • For reversing the queue one approach could be to store the elements of the queue in a temporary data structure in a manner such that if we re-insert the elements in the queue they would get inserted in reverse order. So now our task is to choose such data- structure which can serve the purpose. • According to the approach, the data-structure should have the property of ‘LIFO’ as the last element to be inserted in the data structure should actually be the first element of the reversed queue. • The stack could help in approaching this problem. • This will be a two-step process: – Pop the elements from the queue and insert into the stack. (Topmost element of the stack is the last element of the queue) – Pop the elements of the stack to insert back into the queue. (The last element is the first one to be inserted into the queue) 4/6/2022 1.9 _ Applications of Queue and Reverse Queue 253
  • 254. Thank you 4/6/2022 1.9 _ Applications of Queue and Reverse Queue 254