Student will be able to learn linear data structures concepts in detailed manner. This PPT comprises of the following topics: LIST ADT, Singly Linked List, Doubly Linked List, Circular Linked List, Applications of Linked List, Applications of Stack and Queue, Tower of Hanoi, Balancing Parenthesis
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
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
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
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
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
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
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
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
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
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
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
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
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)
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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