SlideShare a Scribd company logo
1 of 76
Download to read offline
PREPARED BY V.MEENA AP/CSE 1
UNIT – III - LINEAR DATA STRUCTURES
Abstract Data Types (ADTs)- List ADT – Array-Based Implementation- Linked List – Doubly-Linked Lists
– Circular Linked List – Stack ADT- Implementation of Stack-Applications- Queue ADT – Priority Queues
–Queue Implementation – Applications.
Data Structures:
A data structure is a storage that is used to store and organize data. It is a way of arranging data on a
computer so that it can be accessed and updated efficiently. A data structure is not only used for organizing the
data. It is also used for processing, retrieving, and storing data.
Classification of Data Structure:
Data structure can be classified into two categories:
1. Linear data structure
2. Non-Linear data structure
Linear data structure
Data structure in which data elements are arranged sequentially or linearly, where each element is
attached to its previous and next adjacent elements is called a linear data structure.
Examples of linear data structures are array, stack, queue, linked list, etc.
Static data structure
Static data structure has a fixed memory size. It is easier to access the elements in a static data
structure.
Example: Array.
Arrays
Collection of similar type data elements stored at consecutive locations in the memory.
PREPARED BY V.MEENA AP/CSE 2
Advantages
● Individual data elements can be easily
referred.
Limitations
● Wastage of memory space.
Dynamic data structure
Dynamic data structure, the size is not fixed. It can be randomly updated during the runtime which
may be considered efficient concerning the memory (space) complexity of the code.
Examples: queue, stack, Linked list.
Stack (LIFO (Last In-First Out))
It is an ordered collection of elements in which insertion and deletion are at one end. Push
operation is used for adding an element of data on a stack and the pop operation is used for deleting the
data from the stack.
Queue (FIFO(First In-First Out))
This structure is almost similar to the stack as the data is stored sequentially. Front and rear are
the two terms to be used in a queue. Enqueue is the insertion operation and dequeue is the deletion
operation.
PREPARED BY V.MEENA AP/CSE 3
Linked List
Linked lists are the types where the data is stored in the form of nodes which consist of an element
of data and a pointer. The use of the pointer is that it points or directs to the node which is next to the
element in the sequence.
To store data in the form of a list of nodes connected to each other through pointers.
 Each node has two parts – data and pointer to next data
Advantages
● Optimize the use of storage space.Limitations
● Individual elements cannot be referred directly
Non-linear data structure
Data structures where data elements are not placed sequentially or linearly are called non-linear
data structures. In a non-linear data structure, we can’t traverse all the elements in a single run only.
Examples: Trees and graphs.
Trees
A tree data structure consists of various nodes linked together. The structure of a tree is
hierarchical that forms a relationship like that of the parent and a child.
 Represent data containing hierarchical relationship between elements.
 Example: family trees, records and table of contents.
PREPARED BY V.MEENA AP/CSE 4
Applications
● Implementing search algorithms
Graph
Graphs are the types of non-linear data structures which consist of a definite quantity of vertices
and edges. The vertices or the nodes are involved in storing data and the edges show the vertices
relationship.
 It is a linked data structure that comprises of vertices and a group of edges.
 Edges are associated with certain values called weights.
 Helps to compute the cost of traversing the graph through a certain path.
Difference between linear and non-linear data structures:
S.NO Linear Data Structure Non-linear Data Structure
1.
In a linear data structure, data
elements are arranged in a linear
order where each and every
element is attached to its previous
and next adjacent.
In a non-linear data structure, data
elements are attached in hierarchically
manner.
PREPARED BY V.MEENA AP/CSE 5
S.NO Linear Data Structure Non-linear Data Structure
2.
In linear data structure, single level
is involved.
Whereas in non-linear data structure,
multiple levels are involved.
3.
Its implementation is easy in
comparison to non-linear data
structure.
While its implementation is complex in
comparison to linear data structure.
4.
In linear data structure, data
elements can be traversed in a
single run only.
While in non-linear data structure, data
elements can’t be traversed in a single
run only.
5.
In a linear data structure, memory
is not utilized in an efficient way.
While in a non-linear data structure,
memory is utilized in an efficient way.
6.
Its examples are: array, stack,
queue, linked list, etc.
While its examples are: trees and
graphs.
7.
Applications of linear data
structures are mainly in application
software development.
Applications of non-linear data
structures are in Artificial Intelligence
and image processing.
Abstract Data Type
 Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a
set of values and a set of operations.
 The definition of ADT only mentions what operations are to be performed but not how
these operations will be implemented.
 C is not object-oriented, but we can still manage to inject some object-oriented principles
into the design of C code.
 For example, a data structure and its operations can be packaged together into an entity
called an ADT.
 There’s a clean, simple interface between the ADT and the program(s) that use it.
 The lower-level implementation details of the data structure are hidden from view of the
rest of the program.
 An abstract data type (ADT) is a set of operations and mathematical abstractions , which
PREPARED BY V.MEENA AP/CSE 6
can be viewed as how the set of operations is implemented.
 Objects like lists, sets and graphs, along with their operation, can be viewed as abstract data
types, just as integers, real numbers and Booleans.
 It does not specify how data will be organized in memory and what algorithms will be
used for implementing the operations.
 For example, in C, ADTs are implemented mostly using structure.
 These kinds of models are defined in terms of their data items and associated operations.
 We implement ADTs using different methods and logic.
There are mainly three types of ADTs:
Stack
 isFull(), This is used to check whether stack is full or not
 isEmpry(), This is used to check whether stack is empty or not
 push(x), This is used to push x into the stack
 pop(), This is used to delete one element from top of the stack
 peek(), This is used to get the top most element of the stack
 size(), this function is used to get number of elements present into the stack
Queue
 isFull(), This is used to check whether queue is full or not
 isEmpty(), This is used to check whether queue is empty or not
 insert(x), This is used to add x into the queue at the rear end
 delete(), This is used to delete one element from the front end of the queue
 size(), this function is used to get number of elements present into the queue
PREPARED BY V.MEENA AP/CSE 7
List
 size(), this function is used to get number of elements present into the list
 insert(x), this function is used to insert one element into the list
 remove(x), this function is used to remove given element from the list
 get(i), this function is used to get element at position i
 replace(x, y), this function is used to replace x with y value
List ADT
 List is an ordered set of elements.
 Collection of Elements is called as a List A1,A2,A3,……………An
 Where A1→ First Element of the list
An→ Last Element of the list
n→ Size of the List
Features of ADT:
i) Abstraction: The user does not need to know the implementation of the data structure.
ii) Better Conceptualization: ADT gives us a better conceptualization of the real world.
iii) Robust: The program is robust and has the ability to catch errors.
 Modularity
 Divide program into small functions
 Easy to debug and maintain
 Easy to modify
 Reuse
 Define some operations only once and reuse them in
future
 Easy to change the implementation
PREPARED BY V.MEENA AP/CSE 8
 ADT make simple the modification to a program.
 It separates the use of a DS from the details of its implementation.
List ADT
LIST:
A list is a sequential data structure, ie. a collection of items accessible one after another
beginning at the head and ending at the tail.
 It is a widely used data structure for applications which do not need
random access
 Addition and removals can be made at any position in the list
 Lists are normally in the form of a1,a2,a3,……an.
 The size of this list is n.The first element of the list is a1, and the last element is an.
 The position of element ai in a list isi.
 List of size 0 is called as null list.
 A list is a sequence of zero or more elements of a given type. The list is
represented assequence of elements separated by comma.
A1,A2,A3…..AN
where N>0 and A is of type element.
Basic Operations on a List
 Creating a list
 Traversing the list
 Inserting an item in the list
 Deleting an item from the list
 Concatenating two lists into one
Implementation of List:
A list can be implemented in two ways
1. Array list
2. Linked list
1. Storing a list in a static data structure (Array List)
 This implementation stores the list in an array.
 The position of each element is given by an index from 0 to n-1, where n is the number of
elements.
 The element with the index can be accessed in constant time (ie) the time to access does
not depend on the size of the list.
 The time taken to add an element at the end of the list does not depend on the size of the
PREPARED BY V.MEENA AP/CSE 9
list. But the time taken to add an element at any other point in the list depends on the size
of the list because the subsequent elements must be shifted to next index value. So the
additions near the start of the list take longer time than the additions near the middle or
end.
 Similarly when an element is removed, subsequent elements must be shifted to the previous
index value. So removals near the start of the list take longer time than removalsnear the
middle or end of the list.
2. Problems with Array implementation of lists:
 Insertion and deletion are expensive. For example, inserting at position 0 (a new first
element) requires first pushing the entire array down one spot to make room, whereas
deleting the first element requires shifting all the elements in the list up one, so the worst
case of these operations is O(n).
 Even if the array is dynamically allocated, an estimate of the maximum size of the list is
required. Usually this requires a high over-estimate, which wastes considerable space. This
could be a serious limitation, if there are many lists of unknown size.
 Simple arrays are generally not used to implement lists. Because the running time for
insertion and deletion is so slow and the list size must be known in advance
3. Storing a list in a dynamic data structure (Linked List)
 The Linked List is stored as a sequence of linked nodes which are not necessarily
adjacent in memory.
 Each node in a linked list contains data and a reference to the next node
 The list can grow and shrink in size during execution of a program.
 The list can be made just as long as required. It does not waste memory space because
successive elements are connected by pointers.
 The position of each element is given by an index from 0 to n-1, where n is the number of
elements.
 The time taken to access an element with an index depends on the index because each
element of the list must be traversed until the required index is found.
 The time taken to add an element at any point in the list does not depend on the size of
the list, as no shifts are required
 Additions and deletion near the end of the list take longer than additions near the middle
or start of the list. Because the list must be traversed until the required index is found.
Array versus Linked Lists:
1.Arrays are suitable for
- Randomly accessing any element.
- Searching the list for a particular value
- Inserting or deleting an element at the end.
2.Linked lists are suitable for
-Inserting/Deleting an element.
-Applications where sequential access is required.
-In situations where the number of elements cannot be predicted beforehand.
PREPARED BY V.MEENA AP/CSE 10
Array Based Implementation
Array is a collection of specific number of data stored in consecutive memory locations. Array is a
static data structure i.e., the memory should be allocated in advance and the size is fixed. This will
waste the memory space when used space is less than the allocated space.
 Insertion and Deletion operation are expensive.
 It requires more data movements
 Find and Print list operations takes constant time.
Operations on Array
 Insertion
 Deletion
 Merge
 Traversal
 FindInsertion
 It is the process of adding an element into the existing array. It can be done at any
position.
 Insertion at the end is easy as it is done by shifting one position towards right of last
element if it does not exceeds the array size.
Declaration of Array
#define maxsize 10
int list[maxsize], n ;
Create Operation
Create operation is used to create the list with n number of elements .If n exceeds the
array’s maxsize, then elements cannot be inserted into the list. Otherwise the array elements are
stored in the consecutive array locations (i.e.) list [0], list [1] and so on.
void create ( )
{
int i;
printf("nEnter the number of elements to be added in the list:t"); scanf("%d",&n);
printf("nEnter the array elements:t"); for(i=0;i<n;i++)
scanf("%d",&list[i]); }
If n=6,
PREPARED BY V.MEENA AP/CSE 11
Insert Operation
Insert operation is used to insert an element at particular position in the existing list. Inserting
the element in the last position of an array is easy. But inserting the element at a particular
position in an array is quite difficult since it involves all the subsequent elements to be shifted
one position to the right.
Example
i) Insertion at the end:
20 10 30 40
A[0] A[1] A[2] A[3] A[4] A[5]
Insert (Element 70 in location A[4])
20 10 30 40 70
A[0] A[1] A[2] A[3] A[4] A[5]
ii) Insertion at specified position
20 10 30
A[0] A[1] A[2] A[3] A[4] A[5]
Insert(Element 40 in location A[1])
20 10 30
A[0] A[1] A[2] A[3] A[4] A[5]
First shift the last element one position right (from location 2 to 3)
A[0] A[1] A[2] A[3] A[4] A[5]
Shift the element (10) one position right (from location 1 to 2)
20 10 30
A[0] A[1] A[2] A[3] A[4] A[5]
Now insert element (40) at location 1
20 40 10 30
A[0] A[1] A[2] A[3] A[4] A[5]
 Routine to insert an element in an array
void insert(int X, int P, int A[], int N)
{
if(P==N)
printf(“Array overflow”);
20 10 30
PREPARED BY V.MEENA AP/CSE 12
else
{
}
}
for(int i=N-1;i>=P;i--)
A[i+1]=A[i];
A[P]=X;
N=N+1;
Deletion operation on an Array
 It is the process of removing an element from the array at any position
 Routine
int deletion(int P,int A[],int N)
{
if(P==N-1)
temp=A[P];
else
{
}
temp=A[P];
for(i=P;i<N-1;i++)
A[i]=A[i+1];
N=N-1;
return temp;
}
Deleting an element from the end is easy. If an element is to be deleted from any particular
position ,it requires all subsequent element from that position is shifted one position
towards left
PREPARED BY V.MEENA AP/CSE 13
Merge Operation
 It is the process of combining two sorted array into single sorted array.
A[0] A[1] A[2] A[3] A[4] B[0] B[1] B[2] B[3] B[4]
1 2 3 4 6 8
C[0] C[1] C[2] C[3] C[4] C[5] C[6] C[7] C[8] C[9]
 Routine to merge two sorted array
void merge(int a[],int n, int b[],int m)
{
int c[n+m];
int i=j=k=0;
while(i<n&&j<m)
{
if( a[i]<b[j])
{
}
else
{
}
}
c[k] =a[i];
i++;
k++;
c[k]=b[j];
j++;
k++;
while(i<n)
{
c[k] =a[i];
i++;
k++;
}
while(j<m)
{
c[k] =a[i];
j++;
k++;
}
}
Find operation
2 4 6 1 3 8
PREPARED BY V.MEENA AP/CSE 14
 It is the process of searching an element in the given array. If the element is found, it
returns the position of the search element otherwise NULL.
 Routine
int find(int x, int a[], int N)
{
int pos,flag=0;
for(int i=0;i<N;i++)
{
if(x==a[i])
{
flag=1;
pos=i;
break;
}
}
if(flag==1)
printf(“element %d is found at position %d”,x,pos);
else
printf(“Element not found”);
return pos;
}
Display /Traversal operation
 It is the process of visiting the elements in an array.
 traversal( ) operation is used to display all the elements stored in the list. The elements are
stored from the index 0 to n - 1. Using a for loop, the elements in the list are viewed
 Routine
void traversal(int a[],int n)
PREPARED BY V.MEENA AP/CSE 15
{
for(int i=0;i<n;i++)
printf(a[i]);
}
Merits and demerits of array implementation of lists
Merits
 Fast, random access of elements
 Memory efficient – very less amount of memory is required
Demerits
 Insertion and deletion operations are very slow since the elements should be
moved.
 Redundant memory space – difficult to estimate the size of array.
Linked List Implementation
Linked list consists of series of nodes. Each node contains the element and a pointer to its
successor node. The pointer of the last node points to the NULL.
Each node contains two fields
 Data Field(any type)
 Address Field (Pointer to the next node in the list)
Next Pointer
Node
Data element
EC8393/fundamentals of data structures in UNIT III
A linked list consists of nodes where each node contains a data field and a reference(link) to
the next node in the list. Where data field stores the information and link field is used to point to the
next node. Link field contains only address.
Creation of node:
struct Node
{
int data; // integer data
struct Node* next; // pointer to the next node
};
Memory allocation of linked list nodes:
struct Node* newNode(int data)
{
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}
Linked list operations:
Traversal - Access each element of the linked list
Insertion - Adds a new element to the linked list.
Deletion - Removes the existing elements.
Search - Find a node in the linked list.
Traversal:
struct node *temp = head;
printf("nnList elements are - n");
while(temp != NULL) {
printf("%d --->",temp->data);
temp = temp->next;
}
Insert Elements to a Linked List
Insert at the beginning
 Allocate memory for new node
 Store data
 Change next of new node to point to head
EC8393/fundamentals of data structures in UNIT III
 Change head to point to recently created node
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = head;
head = newNode;
Insert at the End
 Allocate memory for new node
 Store data
 Traverse to last node
 Change next of last node to recently created node
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = NULL;
struct node *temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
Insert at the Middle
 Allocate memory and store data for new node
 Traverse to node just before the required position of new node
 Change next pointers to include new node in between
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
struct node *temp = head;
for(int i=2; i < position; i++)
{
if(temp->next != NULL)
{
temp = temp->next;
} }
newNode->next = temp->next;
temp->next = newNode;
Delete from a Linked List
Delete either from the beginning, end or from a particular position.
EC8393/fundamentals of data structures in UNIT III
1. Delete from beginning
Point head to the second node
head = head->next;
2. Delete from end
Traverse to second last element
Change its next pointer to null
struct node* temp = head;
while(temp->next->next!=NULL){
temp = temp->next;
}
temp->next = NULL;
3. Delete from middle
Traverse to element before the element to be deleted
Change next pointers to exclude the node from the chain
for(int i=2; i< position; i++)
{
if(temp->next!=NULL) {
temp = temp->next;
}
}
temp->next = temp->next->next;
Search:
bool searchNode(struct Node** head_ref, int key)
{
struct Node* current = *head_ref;
while (current != NULL)
{
if (current->data == key) return true;
current = current->next;
}
return false;
}
Types of linked list
1. Singly linked list
2. Doubly linked list
3. Circular linked list
EC8393/fundamentals of data structures in UNIT III
Singly Linked Lists
A singly linked list is a linked list in which each node contains only one link field
pointing to the next node in the list.
Doubly Linked Lists
A doubly linked list is a linked list in which each node has three fields namely data field,
forward link(FLINK) and Backward Link(BLINK). FLINK points to the successor node in the list
whereas BLINK points to the predecessor node.
Circular Linked List
In circular linked list the pointer of the last node points to the first node. It can be
implemented as
 Singly linked circular list
 Doubly linked circular list
EC8393/fundamentals of data structures in UNIT III
700 800
40
30
20
10
Singly Linked List
A singly linked list is a linked list in which each node contains only one link field
pointing to the next node in the list.
550 700 1000 80
Declaration for Linked List
struct node;
Routine to insert an element in the List
void Insert(int X,List L, Position P)
{
Position Newnode;
Newnode=malloc(sizeof(struct node));
if(Newnode!=NULL)
{
Newnode→Element=X;
Newnode→Next=P→Next;
P→Next=Newnode;
}
}
Example : Insert(25,L,P)
550
700 800
40
30
20
10
Null
Null
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
800
1200
Routine to check whether the list is empty
int isEmpty(List L) /* returns 1 if L is empty */
{
if(L→Next==NULL)
return 1;
}
Routine to Check whether the current position is Last
int isLast(Position P,List L)
{
if(P→Next==NULL)
return 1;
}
Find Routine
Position Find(int X,List L)
{
Position P;
P=L→Next;
While(P!=NULL && P→Element!=X)
P= P→Next;
return P;
}
FindPrevious Routine
Position FindPrevious(int X,List L)
{
Position P;
P=L;
While(P→Next!=NULL && P→Next
→Element!=X) P= P→Next;
return P;
}
FindNext Routine
Position FindNext(int X,List L)
{
Position P;
P=L→Next;
While(P→Next!=NULL && P→Element!=X)
P= P→Next;
return P→Next;
}
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
typedef struct node *List; typedef struct node *Position;int isLast(List L);
int isEmpty(List L);
Position Find(int X,List L);
void Delete(int X, List L);
Position FindPrevious(int X,List L);
Position FindNext(int X,List L);
void insert(int X,List L, Position P);
void DeleteList(List L);
struct node
{
int Element;
Position Next;
};
Routine to delete an element from the list
void Deletion(int X,List L)
{
Position P,Temp;
P=FindPrevious(X,L);
if(isLast(P,L)
{
Temp= P→Next;
P→Next= Temp→Next;
Free(Temp);
}
}
Routine to delete the list
void DeleteList(List L)
{
Position P,Temp;
P=L→Next;
L→Next=NULL;
while(P!=NULL)
{
Temp=P;
P=P→Next;
Free(Temp);
}
}
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
For Example-2
Here, similary while deleting the desired node
let’s suppose here we want to delete 40, the the first we search the node 40, which want to delete, we also
search its previous node, 30
therefore, after that prev next = temp next
furthermore, we make temp node free, hence, the final list will look like this
Advantages of Singly Linked List
There are some advantages of singly Linked List
 it is very easier for the accessibility of a node in the forward direction.
 the insertion and deletion of a node are very easy.
 the Requirement will less memory when compared to doubly, circular or doubly circular
linked list.
 the Singly linked list is the very easy data structure to implement.
 During the execution, we can allocate or deallocate memory easily.
 Insertion and deletion of elements don’t need the movement of all the elements when
compared to an array.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Disadvantages of Singly Linked List
The disadvantages of singly Linked List are following
 therefore, Accessing the preceding node of a current node is not possible as there is no
backward traversal.
 the Accessing of a node is very time-consuming.
Doubly Linked Lists
A doubly linked list is a linked list in which each node has three fields namely data field,
forward link(FLINK) and Backward Link(BLINK). FLINK points to the successor node in the list
whereas BLINK points to the predecessor node.
BLINK Data Element FLINK
Node in Doubly Linked List
 Doubly Linked List contains a link element called first and last.
 Each link carries a data field(s) and two link fields called next and prev.
 Each link is linked with its next link using its next link.
 Each link is linked with its previous link using its previous link.
 The last link carries a link as null to mark the end of the list.
Basic Operations
 Insertion − Adds an element at the beginning of the list.
 Deletion − Deletes an element at the beginning of the list.
 Insert Last − Adds an element at the end of the list.
 Delete Last − Deletes an element from the end of the list.
 Insert After − Adds an element after an item of the list.
 Delete − Deletes an element from the list using the key.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Structure Declaration
struct node
{
int Element;
struct node *FLINK;
struct node *BLINK;
};
Routine to insert an element in a doubly linked list
void Insert(int X, List L, Position P)
{
struct node *Newnode;
Newnode=malloc(sizeof(struct node));
if(Newnode!=NULL)
{
Newnode→Element = X;
Newnode→Flink = P→Flink;
P→Flink→Blink = Newnode;
P→Flink = Newnode;
Newnode →Blink=P;
}
}
Insertion at the End of an Operation
Example
//insert link at the last location
void insertLast(int key, int data)
{
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if(isEmpty())
{
//make it the last link
last = link;
} else
{
last->next = link;
link->prev = last;
}
last = link;
}
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Routine to delete an element in a doubly linked list
void Deletion(int X,List L)
{
Position P;
if(Find(X,L)
{
}
else
{
}
}
Temp=P;
P→Flink→Blink = NULL;
Free(Temp);
Temp=P;
P →Blink→Flink = P→Flink ;
P→Flink→Blink = P →Blink;
Free(Temp);
Insert Data in the beginning
1. The prev pointer of first node will always be NULL and next will point to front.
2. If the node is inserted is the first node of the list then we make front and end point to this node.
3. Else we only make front point to this node.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Insert Data before a Node
Let’s say we are inserting node X before Y. Then X’s next pointer will point to Y and X’s prev
pointer will point the node Y’s prev pointer is pointing. And Y’s prev pointer will now point to X.
We need to make sure that if Y is the first node of list then after adding X we make front point to
X.
Insert Data after a Node
Let’s say we are inserting node Y after X. Then Y’s prev pointer will point to X and Y’s next
pointer will point the node X’s next pointer is pointing. And X’s next pointer will now point to Y.
We need to make sure that if X is the last node of list then after adding Y we make end point to Y.
Insert Data in the end
1. The next pointer of last node will always be NULL and prev will point to end.
2. If the node is inserted is the first node of the list then we make front and end point to this node.
3. Else we only make end point to this node.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Remove a Node
Removal of a node is quite easy in Doubly linked list but requires special handling if the node to be
deleted is first or last element of the list. Unlike singly linked list where we require the previous
node, here only the node to be deleted is needed. We simply make the next of the previous node
point to next of current node (node to be deleted) and prev of next node point to prev of current
node. Look code for more details.
Advantages
 Deletion operation is easier
 Finding the predecessor and successor of a node is easier.
 Allows us to iterate in both directions.
 We can delete a node easily as we have access to its previous node.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
 Reversing is easy.
 Can grow or shrink in size dynamically.
 Useful in implementing various other data structures.
Disadvantages
 More memory space is required since it has two pointers.
 Compared to a singly linked list, each node store an extra pointer which consumes extra
memory.
 Operations require more time due to the overhead of handling extra pointers as compared
to singly-linked lists.
 No random access of elements.
Singly Linked Circular Lists
Circular Linked List
 In circular linked list the pointer of the last node points to the first node.
 A circular linked list is a sequence of elements in which every element has a link to
its next element in the sequence and the last element has a link to the first element.
It can beimplemented as
 Singly linked circular list
 Doubly linked circular list
Operations
Inserting a New Node in a Circular Linked List
Case 1: The new node is inserted at the beginning of the circular linked list.
Case 2: The new node is inserted at the end of the circular linked list.
Deleting a Node from a Circular Linked List
Case 1: The first node is deleted.
Case2: The last node is deleted
Singly linked circular list
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Implementing Circular Linked List
Implementing a circular linked list is very easy and almost similar to linear linked list
implementation, with the only difference being that, in circular linked list the last Node will have
it's next point to the Head of the List. In Linear linked list the last Node simply holds NULL in it's
next pointer.
class Node {
public:
int data;
//pointer to the next node
node* next;
node() {
data = 0;
next = NULL;
}
node(int x) {
data = x;
next = NULL;
}
}
Insertion in a circular linked list:
A node can be added in three ways:
 Insertion in an empty list
 Insertion at the beginning of the list
 Insertion at the end of the list
 Insertion in between the nodes
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Insertion in an empty List:
Initially, when the list is empty, the last pointer will be NULL.
After inserting node T,
After insertion, T is the last node, so the pointer last points to node T. And Node T is the first
and the last node, so T points to itself.
Circular Linked List
class CircularLinkedList {
public:
node *head;
//declaring the functions
//function to add Node at front
int addAtFront(node *n);
//function to check whether Linked list is empty
int isEmpty();
//function to add Node at the End of list
int addAtEnd(node *n);
//function to search a value
node* search(int k);
//function to delete any Node
node* deleteNode(int x);
CircularLinkedList() {
head = NULL;
}
}
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Insertion at the Beginning
Steps to insert a Node at beginning :
The first Node is the Head for any Linked List.
 When a new Linked List is instantiated, it just has the Head, which is Null.
 Else, the Head holds the pointer to the fisrt Node of the List.
 When we want to add any Node at the front, we must make the head point to it.
 And the Next pointer of the newly added Node, must point to the previous Head, whether it
be NULL(in case of new List) or the pointer to the first Node of the List.
 The previous Head Node is now the second Node of Linked List, because the new Node is
added at the front.
int CircularLinkedList :: addAtFront(node *n) {
int i = 0;
/* If the list is empty */
if(head == NULL) {
n->next = head;
//making the new Node as Head
head = n;
i++;
}
else {
n->next = head;
//get the Last Node and make its next point to new Node
Node* last = getLastNode();
last->next = n;
//also make the head point to the new first Node
head = n;
i++;
}
//returning the position where Node is added
return i;
}
Insertion at the beginning of the list
To insert a node at the beginning of the list, follow these steps:
 Create a node, say T
 Make T -> next = last -> next
 last -> next = T
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
After insertion,
Insertion at the End
Steps to insert a Node at the end :
 If the Linked List is empty then we simply, add the new Node as the Head of the Linked
List.
 If the Linked List is not empty then we find the last node, and make it' next to the new
Node, and make the next of the Newly added Node point to the Head of the List.
int CircularLinkedList :: addAtEnd(node *n) {
//If list is empty
if(head == NULL) {
//making the new Node as Head
head = n;
//making the next pointer of the new Node as Null
n->next = NULL;
}
else {
//getting the last node
node *last = getLastNode();
last->next = n;
//making the next pointer of new node point to head
n->next = head;
}
}
Insertion at the end of the list
To insert a node at the end of the list, follow these steps:
 Create a node, say T
 Make T -> next = last -> next
 last -> next = T
 last = T
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
After insertion
Insertion in between the nodes
To insert a node in between the two nodes, follow these steps:
 Create a node, say T.
 Search for the node after which T needs to be inserted, say that node is P.
 Make T -> next = P -> next;
 P -> next = T.
Suppose 12 needs to be inserted after the node has the value 10,
Searching for an Element in the List
 In searhing we do not have to do much, we just need to traverse like we did while getting
the last node, in this case we will also compare the data of the Node.
 If we get the Node with the same data, we will return it, otherwise we will make our
pointer point the next Node, and so on.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
node* CircularLinkedList :: search(int x) {
node *ptr = head;
while(ptr != NULL && ptr->data != x) {
//until we reach the end or we find a Node with data x, we keep moving
ptr = ptr->next;
}
return ptr;
}
After searching and insertion,
Deleting a Node from the List
Deleting a node can be done in many ways, like we first search the Node with data which
we want to delete and then we delete it. In our approach, we will define a method which will take
the data to be deleted as argument, will use the search method to locate it and will then remove the
Node from the List.
To remove any Node from the list, we need to do the following :
 If the Node to be deleted is the first node, then simply set the Next pointer of the Head to
point to the next element from the Node to be deleted. And update the next pointer of the
Last Node as well.
 If the Node is in the middle somewhere, then find the Node before it, and make the Node
before it point to the Node next to it.
 If the Node is at the end, then remove it and make the new last node point to the head.
node* CircularLinkedList :: deleteNode(int x) {
//searching the Node with data x
node *n = search(x);
node *ptr = head;
if(ptr == NULL) {
cout << "List is empty";
return NULL;
}
else if(ptr == n) {
ptr->next = n->next;
return n;
}
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
else {
while(ptr->next != n) {
ptr = ptr->next;
}
ptr->next = n->next;
return n;
}
Difference between linked list and circular linked listLinked list is a linear data structure that consists
of a group of nodes in a sequence. Each node has got two parts, a data part- which stores the data and an
address part- which stores the address of the next node. Hence forming a chain-like structure. Linked lists
are used to create trees and graphs.
Circular linked list: In a circular linked list, the last node's address part holds the address of the first node
hence forming a circular chain-like structure.
Applications of Circular Linked List
A Circular Linked List can be used for the following –
 Circular lists are used in applications where the entire list is accessed one-by-one in a loop.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
 It is also used by the Operating system to share time for different users, generally uses a Round-
Robin time-sharing mechanism.
 Multiplayer games use a circular list to swap between players in a loop.
 Implementation of Advanced data structures like Fibonacci Heap
 The browser cache which allows you to hit the BACK button
 Undo functionality in Photoshop or Word
 Circular linked lists are used in Round Robin Scheduling
 Circular linked list used Most recent list (MRU LIST)
Advantage of circular linked list
 Entire list can be traversed from any node of the list.
 It saves time when we have to go to the first node from the last node.
 Its is used for the implementation of queue.
 Reference to previous node can easily be found.
 When we want a list to be accessed in a circle or loop then circular linked list are used.
Disadvantage of circular linked list
 Circular list are complex as compared to singly linked lists.
 Reversing of circular list is a complex as compared to singly or doubly lists.
 If not traversed carefully, then we could end up in an infinite loop.
 Like singly and doubly lists circular linked lists also doesn’t support direct accessing of elements.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in
C
UNIT III
Circular Doubly Linked List
The circular doubly linked list is a combination of the doubly linked list and the circular linked
list. It means that this linked list is bidirectional and contains two pointers and the last pointer
points to the first pointer.
Circular Doubly Linked List
A circular doubly linked list is a linear data structure, in which the elements are stored in the form
of a node. Each node contains three sub-elements. A data part that stores the value of the element, the
previous part that stores the pointer to the previous node, and the next part that stores the pointer to the next
node as shown in the below image:
The first node also known as HEAD is always used as a reference to traverse the list. Last element
contains link to the first element as next and the first element contains link of the last element as previous.
A circular doubly linked can be visualized as a chain of nodes, where every node points to previous and
next node.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in
C
UNIT III
Structure Declaration
struct node
{
int Element;
struct node *FLINK;
struct node *BLINK;
};
Routine to insert an element at the beginning
void Insert_beg(int X, List L)
{
Position Newnode;
Newnode=malloc(sizeof(struct node));
if(Newnode!=NULL)
{
Newnode→Element = X;
Newnode→Flink = L→Flink;
L→Flink→Blink = Newnode;
L→Flink = Newnode;
Newnode →Blink=L;
}
}
Routine to insert an element in the middle
void Insert_mid(int X, List L,Position P)
{
Position Newnode;
Newnode=malloc(sizeof(struct node));
if(Newnode!=NULL)
{
Newnode→Element = X;
Newnode→Flink = P→Flink;
P→Flink→Blink = Newnode;
P→Flink = Newnode;
Newnode →Blink=P;
}
}
Routine to insert an element at the last
void Insert_last(int X, List L)
{
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in
C
UNIT III
Position Newnode,P;
Newnode=malloc(sizeof(struct node));
if(Newnode!=NULL)
{
P=L;
While(P→Flink!=NULL)
P= P→Flink;
Newnode→Element = X;
P→Flink = Newnode;
Newnode→Flink = L;
Newnode →Blink=P;
L→Blink = Newnode;
}
}
Routine to delete an element from the beginning
void dele_first(List L)
Sri vidya college of engineering and technology course
material
{
Position Temp;
if(L→Flink! = NULL)
{
Temp= L→Flink ;
L→Flink = Temp→Flink;
Temp→Flink→Blink = L;
free(Temp);
}
}
Routine to delete an element from the middle
void dele_mid(int X,List L)
{
Position P,Temp;
P=FindPrevious(X);
if(!isLast(P,L)
{
Temp= P→Flink ;
P→Flink = Temp→Flink;
Temp→Flink→Blink = P;
free(Temp);
}
}
Routine to delete an element from the last
void dele_last(List L)
{
Position Temp;
P=L;
While(P→Flink!= L)
P= P→Flink;
Temp= P;
P→Blink →Flink = L;
L→Blink = P→Blink;
free(Temp);
}
ALGORITHM
Case 1: Empty List(start = NULL)
 If the list is empty, simply return it.
Case 2: The List initially contains some nodes, start points at the first node of the List
1. If the list is not empty, then we define two pointers curr and prev_1 and initialize the
pointer curr points to the first node of the list, and prev_1 = NULL.
Sri vidya college of engineering and technology course
material
2. Traverse the list using the curr pointer to find the node to be deleted and before moving
from curr to the next node, every time set prev_1 = curr.
3. If the node is found, check if it is the only node in the list. If yes, set start = NULL and free
the node pointing by curr.
4. If the list has more than one node, check if it is the first node of the list. The condition to
check this is (curr == start). If yes, then move prev_1 to the last node(prev_1 = start -> prev).
After prev_1 reaches the last node, set start = start -> next and prev_1 -> next = start and
start -> prev = prev_1. Free the node pointing by curr.
5. If curr is not the first node, we check if it is the last node in the list. The condition to check
this is (curr -> next == start). If yes, set prev_1 -> next = start and start -> prev = prev_1.
Free the node pointing by curr.
6. If the node to be deleted is neither the first node nor the last node, declare one more
pointer temp and initialize the pointer temp points to the next of curr pointer (temp = curr-
>next). Now set, prev_1 -> next = temp and temp ->prev = prev_1. Free the node pointing by
curr.
 If the given key(Say 4) matches with the first node of the list(Step 4):
 If the given key(Say 8) matches with the last node of the list(Step 5):
Sri vidya college of engineering and technology course
material
 If the given key(Say 6) matches with the middle node of the list(Step 6):
Advantages of Circular Doubly Linked List:
 List can be traversed from both directions i.e. from head to tail or from tail to head.
 Ease of data manipulation.
 Jumping from head to tail or vice versa takes O(1) time.
Disadvantages of Circular Doubly Linked List:
 Requires additional memory.
 More complex than singly linked list.
 If not used properly, then the problem of infinite loop can occur.
Applications of Circular Doubly Linked List:
 Implementation of advanced data structures like Fibonacci Heap.
 Used with data where we have to navigate front and back.
 Circular doubly linked lists are used in multiprocessing.
Real-life applications of Circular Doubly Linked List:
 Music Player.
 Shopping-cart on online websites.
 Browser cache.
Sri vidya college of engineering and technology course
material
Stack ADT
 Stack is a specialized data storage structure (Abstract data type).
 Unlike arrays, access of elements in a stack is restricted.
 It has two main functions
o push
o pop
 Insertion in a stack is done using push function and removal from a stack is done using
pop function.
 Stack allows access to only the last element inserted hence, an item can be inserted or
removed from the stack from one end called the top of the stack. It is therefore, also called
Last-In-First-Out (LIFO) list.
 Stack has three properties:
o capacity stands for the maximum number of elements stack can hold
o size stands for the current size of the stack
o elements is the array of elements.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in
C
UNIT III
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in
C
UNIT III
1. createStack function– This function takes the maximum number of elements (maxElements)
the stack can hold as an argument, creates a stack according to it and returns a pointer to the stack.
It initializes Stack S using malloc function and its properties.
2. push function - This function takes the pointer to the top of the stack S and the item (element)
to be inserted as arguments. Check for the emptiness of stack
3. pop function - This function takes the pointer to the top of the stack S as an argument.
4. top function – This function takes the pointer to the top of the stack S as an argumentand
returns the topmost element of the stack S.
Properties of stacks:
1. Each function runs in O(1) time.
2. It has two basic implementations
 Array-based implementation – It is simple and efficient but the maximum size of the
stack is fixed.
 Singly Linked List-based implementation – It’s complicated but there is no limit on the
stack size, it is subjected to the available memory.
Stacks - C Program source code
#include<stdio.h>
#include<stdlib.h>
/* Stack has three properties. capacity stands for the maximum number of elements stack can
hold.
Size stands for the current size of the stack and elements is the array of elements */
typedef struct Stack
{
int capacity;
int size;
int *elements;
}Stack;
/* crateStack function takes argument the maximum number of elements the stack can hold,
creates
a stack according to it and returns a pointer to the stack. */
Stack * createStack(int maxElements)
{
/* Create a Stack */
Stack *S;
S = (Stack *)malloc(sizeof(Stack));
/* Initialise its properties */
S->elements = (int *)malloc(sizeof(int)*maxElements);
S->size = 0;
S->capacity = maxElements;
/* Return the pointer */
return S;
}
void pop(Stack *S)
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in
C
UNIT III
{
/* If stack size is zero then it is empty. So we cannot pop
*/if(S->size==0)
{
printf("Stack is Emptyn");
return;
}
/* Removing an element is equivalent to reducing its size by one */
else
{
S->size--;
}
return;
}
int top(Stack *S)
{
if(S->size==0)
{
printf("Stack is Emptyn");
exit(0);
}
/* Return the topmost element */
return S->elements[S->size-1];
}
void push(Stack *S,int element)
{
/* If the stack is full, we cannot push an element into it as there is no space for it.*/
if(S->size == S->capacity)
{
}
else
{
}
printf("Stack is Fulln");
/* Push an element on the top of it and increase its size by one*/
S->elements[S->size++] = element;
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
return;
}
int main()
{
Stack *S = createStack(5);
push(S,7);
push(S,5);
push(S,21);
push(S,-1);
printf("Top element is %dn",top(S));
pop(S);
printf("Top element is %dn",top(S));
pop(S);
printf("Top element is %dn",top(S));
pop(S);
printf("Top element is %dn",top(S));
}
Evaluation of Arithmetic Expressions
Stacks are useful in evaluation of arithmetic expressions. Consider the expression
5 * 3 +2 + 6 * 4
The expression can be evaluated by first multiplying 5 and 3, storing the result in A, adding 2
and A, saving the result in A. We then multiply 6 and 4 and save the answer in B. We finish off
by adding A and B and leaving the final answer in A.
A = 15 2 +
= 17
B = 6 4 *
= 24
A = 17 24 +
= 41
We can write this sequence of operations as follows:
5 3 * 2 + 6 4 * +
This notation is known as postfix notation and is evaluated as described above. We shall
shortly show how this form can be generated using a stack.
Basically there are 3 types of notations for expressions. The standard form is known as the
infix form. The other two are postfix and prefix forms.
Infix: operator is between operands A + B
Postfix : operator follows operands A B +
Prefix: operator precedes operands + A B
Note that all infix expressions can not be evaluated by using the left to right order of the
operators inside the expression. However, the operators in a postfix expression are ALWAYS in
the correct evaluation order. Thus evaluation of an infix expression is done in two steps.
The first step is to convert it into its equivalent postfix expression. The second step involves
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
evaluation of the postfix expression. We shall see in this section, how stacks are useful in
carrying out both the steps. Let us first examine the basic process of infix to postfix
conversion.
Infix to postfix conversion:
a + b * c Infix form
(precedence of * is higher than of +)
a + (b * c) convert the multiplication
a + ( b c * ) convert the addition
a (b c * ) + Remove parentheses
a b c * + Postfix form
Note that there is no need of parentheses in postfix forms.
Example 2:
( A + B ) * C Infix form
( A B + ) * C Convert the addition
(A B + ) C * Convert multiplication
A B + C * Postfix form
No need of parenthesis anywhere
Example 3:
a + (( b * c ) / d ) 5
a + ( ( b c * ) /d )
(precedence of * and / are same and they are left associative)
a + ( b c * d / )
a b c * d / +
Queue ADT
• It is a linear data structure that maintains a list of elements such that insertion happens at
rear end and deletion happens at front end.
• FIFO – First In First Out principle
Logical Representation of queues:
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Queue implementation:
• Array implementation of queues
• Linked list implementation of queues
Array Implementation of queues:
Insert operation(Enqueue)
• It includes checking whether or not the queue pointer rear is pointing at the upper bound
of the array. If it is not, rear is incremented by 1 and the new item is placed at the end of
the queue.
• Algorithm
insert(queue[max],element, front ,rear)
Step 1 : Start
Step 2 : If front = NULL goto Step 3 else goto Step 6
Step 3 : front = rear = 0
Step 4 : queue[front] = element
Step 5 : Goto Step 10
Step 6 : If rear = MAX-1 goto Step 7 else goto Step 8
Step 7 : Display the message,”Queue is FULL” and goto Step 10
Step 8 : rear = rear + 1
Step 9 : queue[rear] = element
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Step 10 : Stop
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
• Delete operation(Dequeue)
– It includes checking whether or not the queue pointer front is already pointing at
NULL. . If it is not, the item that is being currently pointed is removed from the
queue and front pointer is incremented by 1.
– Algorithm
delete(queue[MAX], front , rear)
Step 1 : Start
Step 2 : If front = NULL and rear =NULL goto Step 3 else goto Step 4
Step 3 : Display the message,”Queue is Empty” and goto Step 10
Step 4 : If front != NULL and front = rear goto Step 5 else goto Step 8
Step 5 : Set I = queue[front]
Step 6 : Set front = rear = -1
Step 7 : Return the deleted element I and goto Step 10
Step 8 : Set i=queue[front]
Step 9 : Return the deleted element i
Step 10 : Stop
Program to implement queues using arrays:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int queue[100];
int front=-1;
int rear=-1;
void insert(int);
int del();
void display();
void main()
{
int choice;
int num1=0,num2=0;
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
while(1)
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
{
case 3:
printf(“n Select a choice from the following : “);
printf(“n[1] Add an element into the queue”);
printf(“n[2] Remove an element from the queue”);
printf(“n[3] Display the queue elements”);
printf(“n[4] Exitn”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:
{
printf(“nEnter the element to be added :”);
scanf(“%d”,&num1);
insert(num1); break;
}
{
num2=del();
if(num2==9999);
else
printf(“n %d element removed from the queue”);
getch(); break;
}
{
display();
getch();
break;
}
Case 4:
Exit(1);
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
break;
default:
printf(“nInvalid choice”);
break;
}
}
}
void display()
{
int i;
if(front==-1)
{
printf(“Queue is empty”);
return;
}
printf(“n The queue elements are :n”);
for(i=front;i<=rear;i++)
printf(“t%d”,queue[i]);
}
void insert(int element)
{
if(front==-1 )
{
front = rear = front +1;
queue[front] = element;
return;
}
if(rear==99)
{
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
printf(“Queue is full”);
getch();
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
return;
}
rear = rear +1;
queue[rear]=element;
}
void insert(int element)
{
if(front==-1 )
{
front = rear = front +1;
queue[front] = element;
return;
}
if(rear==99)
{
printf(“Queue is full”);
getch();
return;
}
rear = rear +1;
queue[rear]=element;
}
Linked Implementation of Queues:
• It is based on the dynamic memory management techniques which allow allocation and
de-allocation of memory space at runtime.
Insert operation:
It involves the following subtasks :
1. Reserving memory space of the size of a queue element in memory
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
2. Storing the added value at the new location
3. Linking the new element with existing queue
4. Updating the rear pointer
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
insert(structure queue, value, front , rear)
Step 1: Start
Step 2: Set ptr = (struct queue*)malloc(sizeof(struct queue))
Step 3 : Set ptr→element=value
Step 4 : if front =NULL goto Step 5 else goto Step 7
Step 5 : Set front =rear = ptr
Step 6 : Set ptr→next = NULL and goto Step 10
Step 7 : Set rear→next = ptr
Step 8 : Set ptr→next =NULL
Step 9 : Set rear = ptr
Step 10 : Stop
Delete operation:
It involves the following subtasks :
1. Checking whether queue is empty
2. Retrieving the front most element of the queue
3. Updating the front pointer
4. Returning the retrieved value
delete(structure queue, front , rear)
Step 1 : Start
Step 2 : if front =NULL goto Step 3 else goto Step 4
Step 3 : Display message, “Queue is empty” and goto Step 7
Step 4 : Set i = front→element
Step 5 : Set front = front→next
Step 6 : Return the deleted element i
Step 7 : Stop
Program to implement queues using linked lists:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
struct queue
{
int element;
struct queue *next;
};
struct queue *front = NULL;
struct queue *rear = NULL;
void insert(int);
int del();
void display();
void main()
{
int choice;
int num1=0,num2=0;
while(1)
{
printf(“n Select a choice from the following : “);
printf(“n[1] Add an element into the queue”);
printf(“n[2] Remove an element from the queue”);
printf(“n[3] Display the queue elements”);
printf(“n[4] Exitn”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:
{
printf(“nEnter the element to be added :”);
scanf(“%d”,&num1);
insert(num1); break;
}
case 2:
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
{
num2=del();
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
if(num2==9999)
;
else
printf(“n %d element removed from the queue”);
getch();
break;
}
case 3:
{
display();
getch();
break;
}
case 4:
exit(1);
break;
default:
printf(“nInvalid choice”);
break;
}
}
}
void insert(int element)
{
struct queue * ptr = (struct queue*)malloc(sizeof(struct queue));
ptr→element=value;
if(front =NULL)
{
front =rear = ptr;
ptr→next = NULL;
}
else
{
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
rear→ne
xt = ptr;
ptr→next
=NULL;
rear =
ptr;
}
}
int del()
{
int i;
if(front == NULL) /*checking whether the queue is empty*/
{
return(-9999);
}
else
{
i =
front→ele
ment;front
=
front→ne
xt;return i;
}
}
void display()
{
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
struct queue
*ptr = front;
if(front==NUL
L)
{
printf(“Queue is
empty”);return;
}
Priority Queue
What is a priority queue?
A priority queue is an abstract data type that behaves similarly to the normal queue
except that each element has some priority, i.e., the element with the highest priority would come
first in a priority queue. The priority of the elements in a priority queue will determine the order
in which elements are removed from the priority queue.
The priority queue supports only comparable elements, which means that the elements
are either arranged in an ascending or descending order.
For example, suppose we have some values like 1, 3, 4, 8, 14, 22 inserted in a priority
queue with an ordering imposed on the values is from least to the greatest. Therefore, the 1
number would be having the highest priority while 22 will be having the lowest priority.
Characteristics of a Priority queue
 A priority queue is an extension of a queue that contains the following characteristics:
 Every element in a priority queue has some priority associated with it.
 An element with the higher priority will be deleted before the deletion of the lesser
priority.
 If two elements in a priority queue have the same priority, they will be arranged using the
FIFO principle.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Let's understand the priority queue through an example.
We have a priority queue that contains the following values:
1, 3, 4, 8, 14, 22
All the values are arranged in ascending order. Now, we will observe how the priority
queue will look after performing the following operations:
 poll(): This function will remove the highest priority element from the priority queue. In
the above priority queue, the '1' element has the highest priority, so it will be removed
from the priority queue.
 add(2): This function will insert '2' element in a priority queue. As 2 is the smallest
element among all the numbers so it will obtain the highest priority.
 poll(): It will remove '2' element from the priority queue as it has the highest priority
queue.
 add(5): It will insert 5 element after 4 as 5 is larger than 4 and lesser than 8, so it will
obtain the third highest priority in a priority queue.
Types of Priority Queue
There are two types of priority queue:
Ascending order priority queue:
In ascending order priority queue, a lower priority number is given as a higher priority in
a priority. For example, we take the numbers from 1 to 5 arranged in an ascending order like
1,2,3,4,5; therefore, the smallest number, i.e., 1 is given as the highest priority in a priority
queue.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Descending order priority queue:
In descending order priority queue, a higher priority number is given as a higher priority
in a priority. For example, we take the numbers from 1 to 5 arranged in descending order like 5,
4, 3, 2, 1; therefore, the largest number, i.e., 5 is given as the highest priority in a priority queue.
Representation of priority queue
Now, we will see how to represent the priority queue through a one-way list.
We will create the priority queue by using the list given below in which INFO list
contains the data elements, PRN list contains the priority numbers of each data element available
in the INFO list, and LINK basically contains the address of the next node.
Let's create the priority queue step by step.
In the case of priority queue, lower priority number is considered the higher priority, i.e., lower
priority number = higher priority.
Step 1: In the list, lower priority number is 1, whose data value is 333, so it will be inserted in
the list as shown in the below diagram:
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Step 2: After inserting 333, priority number 2 is having a higher priority, and data values
associated with this priority are 222 and 111. So, this data will be inserted based on the FIFO
principle; therefore 222 will be added first and then 111.
Step 3: After inserting the elements of priority 2, the next higher priority number is 4 and data
elements associated with 4 priority numbers are 444, 555, 777. In this case, elements would be
inserted based on the FIFO principle; therefore, 444 will be added first, then 555, and then 777.
Step 4: After inserting the elements of priority 4, the next higher priority number is 5, and the
value associated with priority 5 is 666, so it will be inserted at the end of the queue.
Implementation of Priority Queue
The priority queue can be implemented in four ways that include arrays, linked list, heap
data structure and binary search tree. The heap data structure is the most efficient way of
implementing the priority queue, so we will implement the priority queue using a heap data
structure in this topic. Now, first we understand the reason why heap is the most efficient way
among all the other data structures.
Analysis of complexities using different implementations
Implementation add Remove peek
Linked list O(1) O(n) O(n)
Binary heap O(logn) O(logn) O(1)
Binary search tree O(logn) O(logn) O(1)
What is Heap?
A heap is a tree-based data structure that forms a complete binary tree, and satisfies the
heap property. If A is a parent node of B, then A is ordered with respect to the node B for all
nodes A and B in a heap. It means that the value of the parent node could be more than or equal
to the value of the child node, or the value of the parent node could be less than or equal to the
value of the child node. Therefore, we can say that there are two types of heaps:
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Max heap: The max heap is a heap in which the value of the parent node is greater than the
value of the child nodes.
Min heap: The min heap is a heap in which the value of the parent node is less than the value of
the child nodes.
Both the heaps are the binary heap, as each has exactly two child nodes.
Priority Queue Operations
The common operations that we can perform on a priority queue are insertion, deletion and peek.
Let's see how we can maintain the heap data structure.
Inserting the element in a priority queue (max heap)
If we insert an element in a priority queue, it will move to the empty slot by looking from top to
bottom and left to right.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
If the element is not in a correct place then it is compared with the parent node; if it is found out
of order, elements are swapped. This process continues until the element is placed in a correct
position.
Heapify,
Removing the minimum element from the priority queue
As we know that in a max heap, the maximum element is the root node. When we
remove the root node, it creates an empty slot. The last inserted element will be added in this
empty slot. Then, this element is compared with the child nodes, i.e., left-child and right child,
and swap with the smaller of the two. It keeps moving down the tree until the heap property is
restored.
Applications of Priority queue
The following are the applications of the priority queue:
 It is used in the Dijkstra's shortest path algorithm.
 It is used in prim's algorithm
 It is used in data compression techniques like Huffman code.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
 It is used in heap sort.
 It is also used in operating system like priority scheduling, load balancing and interrupt
handling.
Program to create the priority queue using the binary max heap.
#include <stdio.h>
#include <stdio.h>
int heap[40];
int size=-1;
// retrieving the parent node of the child node
int parent(int i)
{
return (i - 1) / 2;
}
// retrieving the left child of the parent node.
int left_child(int i)
{
return i+1;
}
// retrieving the right child of the parent
int right_child(int i)
{
return i+2;
}
// Returning the element having the highest priority
int get_Max()
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
{
return heap[0];
}
//Returning the element having the minimum priority
int get_Min()
{
return heap[size];
}
// function to move the node up the tree in order to restore the heap property.
void moveUp(int i)
{
while (i > 0)
{
// swapping parent node with a child node
if(heap[parent(i)] < heap[i]) {
int temp;
temp=heap[parent(i)];
heap[parent(i)]=heap[i];
heap[i]=temp;
}
// updating the value of i to i/2
i=i/2;
}
}
//function to move the node down the tree in order to restore the heap property.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
void moveDown(int k)
{
int index = k;
// getting the location of the Left Child
int left = left_child(k);
if (left <= size && heap[left] > heap[index]) {
index = left;
}
// getting the location of the Right Child
int right = right_child(k);
if (right <= size && heap[right] > heap[index]) {
index = right;
}
// If k is not equal to index
if (k != index) {
int temp;
temp=heap[index];
heap[index]=heap[k];
heap[k]=temp;
moveDown(index);
}
}
// Removing the element of maximum priority
void removeMax()
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
{
int r= heap[0];
heap[0]=heap[size];
size=size-1;
moveDown(0);
}
//inserting the element in a priority queue
void insert(int p)
{
size = size + 1;
heap[size] = p;
// move Up to maintain heap property
moveUp(size);
}
//Removing the element from the priority queue at a given index i.
void delete(int i)
{
heap[i] = heap[0] + 1;
// move the node stored at ith location is shifted to the root node
moveUp(i);
// Removing the node having maximum priority
removeMax();
}
int main()
{
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
// Inserting the elements in a priority queue
insert(20);
insert(19);
insert(21);
insert(18);
insert(12);
insert(17);
insert(15);
insert(16);
insert(14);
int i=0;
printf("Elements in a priority queue are : ");
for(int i=0;i<=size;i++)
{
printf("%d ",heap[i]);
}
delete(2); // deleting the element whose index is 2.
printf("nElements in a priority queue after deleting the element are : ");
for(int i=0;i<=size;i++)
{
printf("%d ",heap[i]);
}
int max=get_Max();
printf("nThe element which is having the highest priority is %d: ",max);
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
int min=get_Min();
printf("nThe element which is having the minimum priority is : %d",min);
return 0;
}
In the above program, we have created the following functions:
int parent(int i): This function returns the index of the parent node of a child node, i.e., i.
int left_child(int i): This function returns the index of the left child of a given index, i.e., i.
int right_child(int i): This function returns the index of the right child of a given index, i.e., i.
void moveUp(int i): This function will keep moving the node up the tree until the heap property
is restored.
void moveDown(int i): This function will keep moving the node down the tree until the heap
property is restored.
void removeMax(): This function removes the element which is having the highest priority.
void insert(int p): It inserts the element in a priority queue which is passed as an argument in a
function.
void delete(int i): It deletes the element from a priority queue at a given index.
int get_Max(): It returns the element which is having the highest priority, and we know that in
max heap, the root node contains the element which has the largest value, and highest priority.
int get_Min(): It returns the element which is having the minimum priority, and we know that in
max heap, the last node contains the element which has the smallest value, and lowest priority.
Sri vidya college of engineering and technology course
material
EC8393/fundamentals of data structures in UNIT III
Output

More Related Content

Similar to UNITIII LDS.pdf

Introduction to Data Structure
Introduction to Data StructureIntroduction to Data Structure
Introduction to Data StructureJazz Jinia Bhowmik
 
2. Introduction to Data Structure.pdf
2. Introduction to Data Structure.pdf2. Introduction to Data Structure.pdf
2. Introduction to Data Structure.pdfSulabhPawaia
 
data structure details of types and .ppt
data structure details of types and .pptdata structure details of types and .ppt
data structure details of types and .pptpoonamsngr
 
Data_structure.pptx
Data_structure.pptxData_structure.pptx
Data_structure.pptxpriya415376
 
data structure programing language in c.ppt
data structure programing language in c.pptdata structure programing language in c.ppt
data structure programing language in c.pptLavkushGupta12
 
Data structures introduction
Data structures   introductionData structures   introduction
Data structures introductionmaamir farooq
 
Data structure &amp; algorithms introduction
Data structure &amp; algorithms introductionData structure &amp; algorithms introduction
Data structure &amp; algorithms introductionSugandh Wafai
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS Adams Sidibe
 
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCEARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCEVenugopalavarma Raja
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringRAJASEKHARV8
 
Chapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdfChapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdfAxmedcarb
 
Data structures and algorithms short note (version 14).pd
Data structures and algorithms short note (version 14).pdData structures and algorithms short note (version 14).pd
Data structures and algorithms short note (version 14).pdNimmi Weeraddana
 
Data structures - Introduction
Data structures - IntroductionData structures - Introduction
Data structures - IntroductionDeepaThirumurugan
 

Similar to UNITIII LDS.pdf (20)

Introduction to Data Structure
Introduction to Data StructureIntroduction to Data Structure
Introduction to Data Structure
 
2. Introduction to Data Structure.pdf
2. Introduction to Data Structure.pdf2. Introduction to Data Structure.pdf
2. Introduction to Data Structure.pdf
 
data structure details of types and .ppt
data structure details of types and .pptdata structure details of types and .ppt
data structure details of types and .ppt
 
Data_structure.pptx
Data_structure.pptxData_structure.pptx
Data_structure.pptx
 
data structure programing language in c.ppt
data structure programing language in c.pptdata structure programing language in c.ppt
data structure programing language in c.ppt
 
Intro ds
Intro dsIntro ds
Intro ds
 
DSA - Copy.pptx
DSA - Copy.pptxDSA - Copy.pptx
DSA - Copy.pptx
 
Data structures introduction
Data structures   introductionData structures   introduction
Data structures introduction
 
M v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notesM v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notes
 
Data structure &amp; algorithms introduction
Data structure &amp; algorithms introductionData structure &amp; algorithms introduction
Data structure &amp; algorithms introduction
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS
 
PM.ppt
PM.pptPM.ppt
PM.ppt
 
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCEARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
 
PM.ppt
PM.pptPM.ppt
PM.ppt
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
intr_ds.ppt
intr_ds.pptintr_ds.ppt
intr_ds.ppt
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
 
Chapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdfChapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdf
 
Data structures and algorithms short note (version 14).pd
Data structures and algorithms short note (version 14).pdData structures and algorithms short note (version 14).pd
Data structures and algorithms short note (version 14).pd
 
Data structures - Introduction
Data structures - IntroductionData structures - Introduction
Data structures - Introduction
 

Recently uploaded

Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一F La
 
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改yuu sss
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...soniya singh
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Jack DiGiovanna
 
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一F La
 
Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceSapana Sha
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样vhwb25kk
 
Generative AI for Social Good at Open Data Science East 2024
Generative AI for Social Good at Open Data Science East 2024Generative AI for Social Good at Open Data Science East 2024
Generative AI for Social Good at Open Data Science East 2024Colleen Farrelly
 
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一fhwihughh
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort servicejennyeacort
 
RadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfRadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfgstagge
 
How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFAAndrei Kaleshka
 
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档208367051
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...Florian Roscheck
 
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝DelhiRS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhijennyeacort
 
科罗拉多大学波尔得分校毕业证学位证成绩单-可办理
科罗拉多大学波尔得分校毕业证学位证成绩单-可办理科罗拉多大学波尔得分校毕业证学位证成绩单-可办理
科罗拉多大学波尔得分校毕业证学位证成绩单-可办理e4aez8ss
 
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degreeyuu sss
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 
NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...
NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...
NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...Boston Institute of Analytics
 

Recently uploaded (20)

Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
 
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
 
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
 
Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts Service
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
 
Generative AI for Social Good at Open Data Science East 2024
Generative AI for Social Good at Open Data Science East 2024Generative AI for Social Good at Open Data Science East 2024
Generative AI for Social Good at Open Data Science East 2024
 
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
 
RadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfRadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdf
 
How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFA
 
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
 
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝DelhiRS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
 
科罗拉多大学波尔得分校毕业证学位证成绩单-可办理
科罗拉多大学波尔得分校毕业证学位证成绩单-可办理科罗拉多大学波尔得分校毕业证学位证成绩单-可办理
科罗拉多大学波尔得分校毕业证学位证成绩单-可办理
 
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 
NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...
NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...
NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...
 

UNITIII LDS.pdf

  • 1. PREPARED BY V.MEENA AP/CSE 1 UNIT – III - LINEAR DATA STRUCTURES Abstract Data Types (ADTs)- List ADT – Array-Based Implementation- Linked List – Doubly-Linked Lists – Circular Linked List – Stack ADT- Implementation of Stack-Applications- Queue ADT – Priority Queues –Queue Implementation – Applications. Data Structures: A data structure is a storage that is used to store and organize data. It is a way of arranging data on a computer so that it can be accessed and updated efficiently. A data structure is not only used for organizing the data. It is also used for processing, retrieving, and storing data. Classification of Data Structure: Data structure can be classified into two categories: 1. Linear data structure 2. Non-Linear data structure Linear data structure Data structure in which data elements are arranged sequentially or linearly, where each element is attached to its previous and next adjacent elements is called a linear data structure. Examples of linear data structures are array, stack, queue, linked list, etc. Static data structure Static data structure has a fixed memory size. It is easier to access the elements in a static data structure. Example: Array. Arrays Collection of similar type data elements stored at consecutive locations in the memory.
  • 2. PREPARED BY V.MEENA AP/CSE 2 Advantages ● Individual data elements can be easily referred. Limitations ● Wastage of memory space. Dynamic data structure Dynamic data structure, the size is not fixed. It can be randomly updated during the runtime which may be considered efficient concerning the memory (space) complexity of the code. Examples: queue, stack, Linked list. Stack (LIFO (Last In-First Out)) It is an ordered collection of elements in which insertion and deletion are at one end. Push operation is used for adding an element of data on a stack and the pop operation is used for deleting the data from the stack. Queue (FIFO(First In-First Out)) This structure is almost similar to the stack as the data is stored sequentially. Front and rear are the two terms to be used in a queue. Enqueue is the insertion operation and dequeue is the deletion operation.
  • 3. PREPARED BY V.MEENA AP/CSE 3 Linked List Linked lists are the types where the data is stored in the form of nodes which consist of an element of data and a pointer. The use of the pointer is that it points or directs to the node which is next to the element in the sequence. To store data in the form of a list of nodes connected to each other through pointers.  Each node has two parts – data and pointer to next data Advantages ● Optimize the use of storage space.Limitations ● Individual elements cannot be referred directly Non-linear data structure Data structures where data elements are not placed sequentially or linearly are called non-linear data structures. In a non-linear data structure, we can’t traverse all the elements in a single run only. Examples: Trees and graphs. Trees A tree data structure consists of various nodes linked together. The structure of a tree is hierarchical that forms a relationship like that of the parent and a child.  Represent data containing hierarchical relationship between elements.  Example: family trees, records and table of contents.
  • 4. PREPARED BY V.MEENA AP/CSE 4 Applications ● Implementing search algorithms Graph Graphs are the types of non-linear data structures which consist of a definite quantity of vertices and edges. The vertices or the nodes are involved in storing data and the edges show the vertices relationship.  It is a linked data structure that comprises of vertices and a group of edges.  Edges are associated with certain values called weights.  Helps to compute the cost of traversing the graph through a certain path. Difference between linear and non-linear data structures: S.NO Linear Data Structure Non-linear Data Structure 1. In a linear data structure, data elements are arranged in a linear order where each and every element is attached to its previous and next adjacent. In a non-linear data structure, data elements are attached in hierarchically manner.
  • 5. PREPARED BY V.MEENA AP/CSE 5 S.NO Linear Data Structure Non-linear Data Structure 2. In linear data structure, single level is involved. Whereas in non-linear data structure, multiple levels are involved. 3. Its implementation is easy in comparison to non-linear data structure. While its implementation is complex in comparison to linear data structure. 4. In linear data structure, data elements can be traversed in a single run only. While in non-linear data structure, data elements can’t be traversed in a single run only. 5. In a linear data structure, memory is not utilized in an efficient way. While in a non-linear data structure, memory is utilized in an efficient way. 6. Its examples are: array, stack, queue, linked list, etc. While its examples are: trees and graphs. 7. Applications of linear data structures are mainly in application software development. Applications of non-linear data structures are in Artificial Intelligence and image processing. Abstract Data Type  Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a set of values and a set of operations.  The definition of ADT only mentions what operations are to be performed but not how these operations will be implemented.  C is not object-oriented, but we can still manage to inject some object-oriented principles into the design of C code.  For example, a data structure and its operations can be packaged together into an entity called an ADT.  There’s a clean, simple interface between the ADT and the program(s) that use it.  The lower-level implementation details of the data structure are hidden from view of the rest of the program.  An abstract data type (ADT) is a set of operations and mathematical abstractions , which
  • 6. PREPARED BY V.MEENA AP/CSE 6 can be viewed as how the set of operations is implemented.  Objects like lists, sets and graphs, along with their operation, can be viewed as abstract data types, just as integers, real numbers and Booleans.  It does not specify how data will be organized in memory and what algorithms will be used for implementing the operations.  For example, in C, ADTs are implemented mostly using structure.  These kinds of models are defined in terms of their data items and associated operations.  We implement ADTs using different methods and logic. There are mainly three types of ADTs: Stack  isFull(), This is used to check whether stack is full or not  isEmpry(), This is used to check whether stack is empty or not  push(x), This is used to push x into the stack  pop(), This is used to delete one element from top of the stack  peek(), This is used to get the top most element of the stack  size(), this function is used to get number of elements present into the stack Queue  isFull(), This is used to check whether queue is full or not  isEmpty(), This is used to check whether queue is empty or not  insert(x), This is used to add x into the queue at the rear end  delete(), This is used to delete one element from the front end of the queue  size(), this function is used to get number of elements present into the queue
  • 7. PREPARED BY V.MEENA AP/CSE 7 List  size(), this function is used to get number of elements present into the list  insert(x), this function is used to insert one element into the list  remove(x), this function is used to remove given element from the list  get(i), this function is used to get element at position i  replace(x, y), this function is used to replace x with y value List ADT  List is an ordered set of elements.  Collection of Elements is called as a List A1,A2,A3,……………An  Where A1→ First Element of the list An→ Last Element of the list n→ Size of the List Features of ADT: i) Abstraction: The user does not need to know the implementation of the data structure. ii) Better Conceptualization: ADT gives us a better conceptualization of the real world. iii) Robust: The program is robust and has the ability to catch errors.  Modularity  Divide program into small functions  Easy to debug and maintain  Easy to modify  Reuse  Define some operations only once and reuse them in future  Easy to change the implementation
  • 8. PREPARED BY V.MEENA AP/CSE 8  ADT make simple the modification to a program.  It separates the use of a DS from the details of its implementation. List ADT LIST: A list is a sequential data structure, ie. a collection of items accessible one after another beginning at the head and ending at the tail.  It is a widely used data structure for applications which do not need random access  Addition and removals can be made at any position in the list  Lists are normally in the form of a1,a2,a3,……an.  The size of this list is n.The first element of the list is a1, and the last element is an.  The position of element ai in a list isi.  List of size 0 is called as null list.  A list is a sequence of zero or more elements of a given type. The list is represented assequence of elements separated by comma. A1,A2,A3…..AN where N>0 and A is of type element. Basic Operations on a List  Creating a list  Traversing the list  Inserting an item in the list  Deleting an item from the list  Concatenating two lists into one Implementation of List: A list can be implemented in two ways 1. Array list 2. Linked list 1. Storing a list in a static data structure (Array List)  This implementation stores the list in an array.  The position of each element is given by an index from 0 to n-1, where n is the number of elements.  The element with the index can be accessed in constant time (ie) the time to access does not depend on the size of the list.  The time taken to add an element at the end of the list does not depend on the size of the
  • 9. PREPARED BY V.MEENA AP/CSE 9 list. But the time taken to add an element at any other point in the list depends on the size of the list because the subsequent elements must be shifted to next index value. So the additions near the start of the list take longer time than the additions near the middle or end.  Similarly when an element is removed, subsequent elements must be shifted to the previous index value. So removals near the start of the list take longer time than removalsnear the middle or end of the list. 2. Problems with Array implementation of lists:  Insertion and deletion are expensive. For example, inserting at position 0 (a new first element) requires first pushing the entire array down one spot to make room, whereas deleting the first element requires shifting all the elements in the list up one, so the worst case of these operations is O(n).  Even if the array is dynamically allocated, an estimate of the maximum size of the list is required. Usually this requires a high over-estimate, which wastes considerable space. This could be a serious limitation, if there are many lists of unknown size.  Simple arrays are generally not used to implement lists. Because the running time for insertion and deletion is so slow and the list size must be known in advance 3. Storing a list in a dynamic data structure (Linked List)  The Linked List is stored as a sequence of linked nodes which are not necessarily adjacent in memory.  Each node in a linked list contains data and a reference to the next node  The list can grow and shrink in size during execution of a program.  The list can be made just as long as required. It does not waste memory space because successive elements are connected by pointers.  The position of each element is given by an index from 0 to n-1, where n is the number of elements.  The time taken to access an element with an index depends on the index because each element of the list must be traversed until the required index is found.  The time taken to add an element at any point in the list does not depend on the size of the list, as no shifts are required  Additions and deletion near the end of the list take longer than additions near the middle or start of the list. Because the list must be traversed until the required index is found. Array versus Linked Lists: 1.Arrays are suitable for - Randomly accessing any element. - Searching the list for a particular value - Inserting or deleting an element at the end. 2.Linked lists are suitable for -Inserting/Deleting an element. -Applications where sequential access is required. -In situations where the number of elements cannot be predicted beforehand.
  • 10. PREPARED BY V.MEENA AP/CSE 10 Array Based Implementation Array is a collection of specific number of data stored in consecutive memory locations. Array is a static data structure i.e., the memory should be allocated in advance and the size is fixed. This will waste the memory space when used space is less than the allocated space.  Insertion and Deletion operation are expensive.  It requires more data movements  Find and Print list operations takes constant time. Operations on Array  Insertion  Deletion  Merge  Traversal  FindInsertion  It is the process of adding an element into the existing array. It can be done at any position.  Insertion at the end is easy as it is done by shifting one position towards right of last element if it does not exceeds the array size. Declaration of Array #define maxsize 10 int list[maxsize], n ; Create Operation Create operation is used to create the list with n number of elements .If n exceeds the array’s maxsize, then elements cannot be inserted into the list. Otherwise the array elements are stored in the consecutive array locations (i.e.) list [0], list [1] and so on. void create ( ) { int i; printf("nEnter the number of elements to be added in the list:t"); scanf("%d",&n); printf("nEnter the array elements:t"); for(i=0;i<n;i++) scanf("%d",&list[i]); } If n=6,
  • 11. PREPARED BY V.MEENA AP/CSE 11 Insert Operation Insert operation is used to insert an element at particular position in the existing list. Inserting the element in the last position of an array is easy. But inserting the element at a particular position in an array is quite difficult since it involves all the subsequent elements to be shifted one position to the right. Example i) Insertion at the end: 20 10 30 40 A[0] A[1] A[2] A[3] A[4] A[5] Insert (Element 70 in location A[4]) 20 10 30 40 70 A[0] A[1] A[2] A[3] A[4] A[5] ii) Insertion at specified position 20 10 30 A[0] A[1] A[2] A[3] A[4] A[5] Insert(Element 40 in location A[1]) 20 10 30 A[0] A[1] A[2] A[3] A[4] A[5] First shift the last element one position right (from location 2 to 3) A[0] A[1] A[2] A[3] A[4] A[5] Shift the element (10) one position right (from location 1 to 2) 20 10 30 A[0] A[1] A[2] A[3] A[4] A[5] Now insert element (40) at location 1 20 40 10 30 A[0] A[1] A[2] A[3] A[4] A[5]  Routine to insert an element in an array void insert(int X, int P, int A[], int N) { if(P==N) printf(“Array overflow”); 20 10 30
  • 12. PREPARED BY V.MEENA AP/CSE 12 else { } } for(int i=N-1;i>=P;i--) A[i+1]=A[i]; A[P]=X; N=N+1; Deletion operation on an Array  It is the process of removing an element from the array at any position  Routine int deletion(int P,int A[],int N) { if(P==N-1) temp=A[P]; else { } temp=A[P]; for(i=P;i<N-1;i++) A[i]=A[i+1]; N=N-1; return temp; } Deleting an element from the end is easy. If an element is to be deleted from any particular position ,it requires all subsequent element from that position is shifted one position towards left
  • 13. PREPARED BY V.MEENA AP/CSE 13 Merge Operation  It is the process of combining two sorted array into single sorted array. A[0] A[1] A[2] A[3] A[4] B[0] B[1] B[2] B[3] B[4] 1 2 3 4 6 8 C[0] C[1] C[2] C[3] C[4] C[5] C[6] C[7] C[8] C[9]  Routine to merge two sorted array void merge(int a[],int n, int b[],int m) { int c[n+m]; int i=j=k=0; while(i<n&&j<m) { if( a[i]<b[j]) { } else { } } c[k] =a[i]; i++; k++; c[k]=b[j]; j++; k++; while(i<n) { c[k] =a[i]; i++; k++; } while(j<m) { c[k] =a[i]; j++; k++; } } Find operation 2 4 6 1 3 8
  • 14. PREPARED BY V.MEENA AP/CSE 14  It is the process of searching an element in the given array. If the element is found, it returns the position of the search element otherwise NULL.  Routine int find(int x, int a[], int N) { int pos,flag=0; for(int i=0;i<N;i++) { if(x==a[i]) { flag=1; pos=i; break; } } if(flag==1) printf(“element %d is found at position %d”,x,pos); else printf(“Element not found”); return pos; } Display /Traversal operation  It is the process of visiting the elements in an array.  traversal( ) operation is used to display all the elements stored in the list. The elements are stored from the index 0 to n - 1. Using a for loop, the elements in the list are viewed  Routine void traversal(int a[],int n)
  • 15. PREPARED BY V.MEENA AP/CSE 15 { for(int i=0;i<n;i++) printf(a[i]); } Merits and demerits of array implementation of lists Merits  Fast, random access of elements  Memory efficient – very less amount of memory is required Demerits  Insertion and deletion operations are very slow since the elements should be moved.  Redundant memory space – difficult to estimate the size of array. Linked List Implementation Linked list consists of series of nodes. Each node contains the element and a pointer to its successor node. The pointer of the last node points to the NULL. Each node contains two fields  Data Field(any type)  Address Field (Pointer to the next node in the list) Next Pointer Node Data element
  • 16. EC8393/fundamentals of data structures in UNIT III A linked list consists of nodes where each node contains a data field and a reference(link) to the next node in the list. Where data field stores the information and link field is used to point to the next node. Link field contains only address. Creation of node: struct Node { int data; // integer data struct Node* next; // pointer to the next node }; Memory allocation of linked list nodes: struct Node* newNode(int data) { struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->data = data; node->next = NULL; return node; } Linked list operations: Traversal - Access each element of the linked list Insertion - Adds a new element to the linked list. Deletion - Removes the existing elements. Search - Find a node in the linked list. Traversal: struct node *temp = head; printf("nnList elements are - n"); while(temp != NULL) { printf("%d --->",temp->data); temp = temp->next; } Insert Elements to a Linked List Insert at the beginning  Allocate memory for new node  Store data  Change next of new node to point to head
  • 17. EC8393/fundamentals of data structures in UNIT III  Change head to point to recently created node struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; newNode->next = head; head = newNode; Insert at the End  Allocate memory for new node  Store data  Traverse to last node  Change next of last node to recently created node struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; newNode->next = NULL; struct node *temp = head; while(temp->next != NULL) { temp = temp->next; } temp->next = newNode; Insert at the Middle  Allocate memory and store data for new node  Traverse to node just before the required position of new node  Change next pointers to include new node in between struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; struct node *temp = head; for(int i=2; i < position; i++) { if(temp->next != NULL) { temp = temp->next; } } newNode->next = temp->next; temp->next = newNode; Delete from a Linked List Delete either from the beginning, end or from a particular position.
  • 18. EC8393/fundamentals of data structures in UNIT III 1. Delete from beginning Point head to the second node head = head->next; 2. Delete from end Traverse to second last element Change its next pointer to null struct node* temp = head; while(temp->next->next!=NULL){ temp = temp->next; } temp->next = NULL; 3. Delete from middle Traverse to element before the element to be deleted Change next pointers to exclude the node from the chain for(int i=2; i< position; i++) { if(temp->next!=NULL) { temp = temp->next; } } temp->next = temp->next->next; Search: bool searchNode(struct Node** head_ref, int key) { struct Node* current = *head_ref; while (current != NULL) { if (current->data == key) return true; current = current->next; } return false; } Types of linked list 1. Singly linked list 2. Doubly linked list 3. Circular linked list
  • 19. EC8393/fundamentals of data structures in UNIT III Singly Linked Lists A singly linked list is a linked list in which each node contains only one link field pointing to the next node in the list. Doubly Linked Lists A doubly linked list is a linked list in which each node has three fields namely data field, forward link(FLINK) and Backward Link(BLINK). FLINK points to the successor node in the list whereas BLINK points to the predecessor node. Circular Linked List In circular linked list the pointer of the last node points to the first node. It can be implemented as  Singly linked circular list  Doubly linked circular list
  • 20. EC8393/fundamentals of data structures in UNIT III 700 800 40 30 20 10 Singly Linked List A singly linked list is a linked list in which each node contains only one link field pointing to the next node in the list. 550 700 1000 80 Declaration for Linked List struct node; Routine to insert an element in the List void Insert(int X,List L, Position P) { Position Newnode; Newnode=malloc(sizeof(struct node)); if(Newnode!=NULL) { Newnode→Element=X; Newnode→Next=P→Next; P→Next=Newnode; } } Example : Insert(25,L,P) 550 700 800 40 30 20 10 Null Null
  • 21. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III 800 1200 Routine to check whether the list is empty int isEmpty(List L) /* returns 1 if L is empty */ { if(L→Next==NULL) return 1; } Routine to Check whether the current position is Last int isLast(Position P,List L) { if(P→Next==NULL) return 1; } Find Routine Position Find(int X,List L) { Position P; P=L→Next; While(P!=NULL && P→Element!=X) P= P→Next; return P; } FindPrevious Routine Position FindPrevious(int X,List L) { Position P; P=L; While(P→Next!=NULL && P→Next →Element!=X) P= P→Next; return P; } FindNext Routine Position FindNext(int X,List L) { Position P; P=L→Next; While(P→Next!=NULL && P→Element!=X) P= P→Next; return P→Next; }
  • 22. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III typedef struct node *List; typedef struct node *Position;int isLast(List L); int isEmpty(List L); Position Find(int X,List L); void Delete(int X, List L); Position FindPrevious(int X,List L); Position FindNext(int X,List L); void insert(int X,List L, Position P); void DeleteList(List L); struct node { int Element; Position Next; }; Routine to delete an element from the list void Deletion(int X,List L) { Position P,Temp; P=FindPrevious(X,L); if(isLast(P,L) { Temp= P→Next; P→Next= Temp→Next; Free(Temp); } } Routine to delete the list void DeleteList(List L) { Position P,Temp; P=L→Next; L→Next=NULL; while(P!=NULL) { Temp=P; P=P→Next; Free(Temp); } }
  • 23. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III For Example-2 Here, similary while deleting the desired node let’s suppose here we want to delete 40, the the first we search the node 40, which want to delete, we also search its previous node, 30 therefore, after that prev next = temp next furthermore, we make temp node free, hence, the final list will look like this Advantages of Singly Linked List There are some advantages of singly Linked List  it is very easier for the accessibility of a node in the forward direction.  the insertion and deletion of a node are very easy.  the Requirement will less memory when compared to doubly, circular or doubly circular linked list.  the Singly linked list is the very easy data structure to implement.  During the execution, we can allocate or deallocate memory easily.  Insertion and deletion of elements don’t need the movement of all the elements when compared to an array.
  • 24. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Disadvantages of Singly Linked List The disadvantages of singly Linked List are following  therefore, Accessing the preceding node of a current node is not possible as there is no backward traversal.  the Accessing of a node is very time-consuming. Doubly Linked Lists A doubly linked list is a linked list in which each node has three fields namely data field, forward link(FLINK) and Backward Link(BLINK). FLINK points to the successor node in the list whereas BLINK points to the predecessor node. BLINK Data Element FLINK Node in Doubly Linked List  Doubly Linked List contains a link element called first and last.  Each link carries a data field(s) and two link fields called next and prev.  Each link is linked with its next link using its next link.  Each link is linked with its previous link using its previous link.  The last link carries a link as null to mark the end of the list. Basic Operations  Insertion − Adds an element at the beginning of the list.  Deletion − Deletes an element at the beginning of the list.  Insert Last − Adds an element at the end of the list.  Delete Last − Deletes an element from the end of the list.  Insert After − Adds an element after an item of the list.  Delete − Deletes an element from the list using the key.
  • 25. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Structure Declaration struct node { int Element; struct node *FLINK; struct node *BLINK; }; Routine to insert an element in a doubly linked list void Insert(int X, List L, Position P) { struct node *Newnode; Newnode=malloc(sizeof(struct node)); if(Newnode!=NULL) { Newnode→Element = X; Newnode→Flink = P→Flink; P→Flink→Blink = Newnode; P→Flink = Newnode; Newnode →Blink=P; } } Insertion at the End of an Operation Example //insert link at the last location void insertLast(int key, int data) { struct node *link = (struct node*) malloc(sizeof(struct node)); link->key = key; link->data = data; if(isEmpty()) { //make it the last link last = link; } else { last->next = link; link->prev = last; } last = link; }
  • 26. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Routine to delete an element in a doubly linked list void Deletion(int X,List L) { Position P; if(Find(X,L) { } else { } } Temp=P; P→Flink→Blink = NULL; Free(Temp); Temp=P; P →Blink→Flink = P→Flink ; P→Flink→Blink = P →Blink; Free(Temp); Insert Data in the beginning 1. The prev pointer of first node will always be NULL and next will point to front. 2. If the node is inserted is the first node of the list then we make front and end point to this node. 3. Else we only make front point to this node.
  • 27. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Insert Data before a Node Let’s say we are inserting node X before Y. Then X’s next pointer will point to Y and X’s prev pointer will point the node Y’s prev pointer is pointing. And Y’s prev pointer will now point to X. We need to make sure that if Y is the first node of list then after adding X we make front point to X. Insert Data after a Node Let’s say we are inserting node Y after X. Then Y’s prev pointer will point to X and Y’s next pointer will point the node X’s next pointer is pointing. And X’s next pointer will now point to Y. We need to make sure that if X is the last node of list then after adding Y we make end point to Y. Insert Data in the end 1. The next pointer of last node will always be NULL and prev will point to end. 2. If the node is inserted is the first node of the list then we make front and end point to this node. 3. Else we only make end point to this node.
  • 28. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Remove a Node Removal of a node is quite easy in Doubly linked list but requires special handling if the node to be deleted is first or last element of the list. Unlike singly linked list where we require the previous node, here only the node to be deleted is needed. We simply make the next of the previous node point to next of current node (node to be deleted) and prev of next node point to prev of current node. Look code for more details. Advantages  Deletion operation is easier  Finding the predecessor and successor of a node is easier.  Allows us to iterate in both directions.  We can delete a node easily as we have access to its previous node.
  • 29. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III  Reversing is easy.  Can grow or shrink in size dynamically.  Useful in implementing various other data structures. Disadvantages  More memory space is required since it has two pointers.  Compared to a singly linked list, each node store an extra pointer which consumes extra memory.  Operations require more time due to the overhead of handling extra pointers as compared to singly-linked lists.  No random access of elements. Singly Linked Circular Lists Circular Linked List  In circular linked list the pointer of the last node points to the first node.  A circular linked list is a sequence of elements in which every element has a link to its next element in the sequence and the last element has a link to the first element. It can beimplemented as  Singly linked circular list  Doubly linked circular list Operations Inserting a New Node in a Circular Linked List Case 1: The new node is inserted at the beginning of the circular linked list. Case 2: The new node is inserted at the end of the circular linked list. Deleting a Node from a Circular Linked List Case 1: The first node is deleted. Case2: The last node is deleted Singly linked circular list
  • 30. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Implementing Circular Linked List Implementing a circular linked list is very easy and almost similar to linear linked list implementation, with the only difference being that, in circular linked list the last Node will have it's next point to the Head of the List. In Linear linked list the last Node simply holds NULL in it's next pointer. class Node { public: int data; //pointer to the next node node* next; node() { data = 0; next = NULL; } node(int x) { data = x; next = NULL; } } Insertion in a circular linked list: A node can be added in three ways:  Insertion in an empty list  Insertion at the beginning of the list  Insertion at the end of the list  Insertion in between the nodes
  • 31. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Insertion in an empty List: Initially, when the list is empty, the last pointer will be NULL. After inserting node T, After insertion, T is the last node, so the pointer last points to node T. And Node T is the first and the last node, so T points to itself. Circular Linked List class CircularLinkedList { public: node *head; //declaring the functions //function to add Node at front int addAtFront(node *n); //function to check whether Linked list is empty int isEmpty(); //function to add Node at the End of list int addAtEnd(node *n); //function to search a value node* search(int k); //function to delete any Node node* deleteNode(int x); CircularLinkedList() { head = NULL; } }
  • 32. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Insertion at the Beginning Steps to insert a Node at beginning : The first Node is the Head for any Linked List.  When a new Linked List is instantiated, it just has the Head, which is Null.  Else, the Head holds the pointer to the fisrt Node of the List.  When we want to add any Node at the front, we must make the head point to it.  And the Next pointer of the newly added Node, must point to the previous Head, whether it be NULL(in case of new List) or the pointer to the first Node of the List.  The previous Head Node is now the second Node of Linked List, because the new Node is added at the front. int CircularLinkedList :: addAtFront(node *n) { int i = 0; /* If the list is empty */ if(head == NULL) { n->next = head; //making the new Node as Head head = n; i++; } else { n->next = head; //get the Last Node and make its next point to new Node Node* last = getLastNode(); last->next = n; //also make the head point to the new first Node head = n; i++; } //returning the position where Node is added return i; } Insertion at the beginning of the list To insert a node at the beginning of the list, follow these steps:  Create a node, say T  Make T -> next = last -> next  last -> next = T
  • 33. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III After insertion, Insertion at the End Steps to insert a Node at the end :  If the Linked List is empty then we simply, add the new Node as the Head of the Linked List.  If the Linked List is not empty then we find the last node, and make it' next to the new Node, and make the next of the Newly added Node point to the Head of the List. int CircularLinkedList :: addAtEnd(node *n) { //If list is empty if(head == NULL) { //making the new Node as Head head = n; //making the next pointer of the new Node as Null n->next = NULL; } else { //getting the last node node *last = getLastNode(); last->next = n; //making the next pointer of new node point to head n->next = head; } } Insertion at the end of the list To insert a node at the end of the list, follow these steps:  Create a node, say T  Make T -> next = last -> next  last -> next = T  last = T
  • 34. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III After insertion Insertion in between the nodes To insert a node in between the two nodes, follow these steps:  Create a node, say T.  Search for the node after which T needs to be inserted, say that node is P.  Make T -> next = P -> next;  P -> next = T. Suppose 12 needs to be inserted after the node has the value 10, Searching for an Element in the List  In searhing we do not have to do much, we just need to traverse like we did while getting the last node, in this case we will also compare the data of the Node.  If we get the Node with the same data, we will return it, otherwise we will make our pointer point the next Node, and so on.
  • 35. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III node* CircularLinkedList :: search(int x) { node *ptr = head; while(ptr != NULL && ptr->data != x) { //until we reach the end or we find a Node with data x, we keep moving ptr = ptr->next; } return ptr; } After searching and insertion, Deleting a Node from the List Deleting a node can be done in many ways, like we first search the Node with data which we want to delete and then we delete it. In our approach, we will define a method which will take the data to be deleted as argument, will use the search method to locate it and will then remove the Node from the List. To remove any Node from the list, we need to do the following :  If the Node to be deleted is the first node, then simply set the Next pointer of the Head to point to the next element from the Node to be deleted. And update the next pointer of the Last Node as well.  If the Node is in the middle somewhere, then find the Node before it, and make the Node before it point to the Node next to it.  If the Node is at the end, then remove it and make the new last node point to the head. node* CircularLinkedList :: deleteNode(int x) { //searching the Node with data x node *n = search(x); node *ptr = head; if(ptr == NULL) { cout << "List is empty"; return NULL; } else if(ptr == n) { ptr->next = n->next; return n; }
  • 36. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III else { while(ptr->next != n) { ptr = ptr->next; } ptr->next = n->next; return n; } Difference between linked list and circular linked listLinked list is a linear data structure that consists of a group of nodes in a sequence. Each node has got two parts, a data part- which stores the data and an address part- which stores the address of the next node. Hence forming a chain-like structure. Linked lists are used to create trees and graphs. Circular linked list: In a circular linked list, the last node's address part holds the address of the first node hence forming a circular chain-like structure. Applications of Circular Linked List A Circular Linked List can be used for the following –  Circular lists are used in applications where the entire list is accessed one-by-one in a loop.
  • 37. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III  It is also used by the Operating system to share time for different users, generally uses a Round- Robin time-sharing mechanism.  Multiplayer games use a circular list to swap between players in a loop.  Implementation of Advanced data structures like Fibonacci Heap  The browser cache which allows you to hit the BACK button  Undo functionality in Photoshop or Word  Circular linked lists are used in Round Robin Scheduling  Circular linked list used Most recent list (MRU LIST) Advantage of circular linked list  Entire list can be traversed from any node of the list.  It saves time when we have to go to the first node from the last node.  Its is used for the implementation of queue.  Reference to previous node can easily be found.  When we want a list to be accessed in a circle or loop then circular linked list are used. Disadvantage of circular linked list  Circular list are complex as compared to singly linked lists.  Reversing of circular list is a complex as compared to singly or doubly lists.  If not traversed carefully, then we could end up in an infinite loop.  Like singly and doubly lists circular linked lists also doesn’t support direct accessing of elements.
  • 38. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in C UNIT III Circular Doubly Linked List The circular doubly linked list is a combination of the doubly linked list and the circular linked list. It means that this linked list is bidirectional and contains two pointers and the last pointer points to the first pointer. Circular Doubly Linked List A circular doubly linked list is a linear data structure, in which the elements are stored in the form of a node. Each node contains three sub-elements. A data part that stores the value of the element, the previous part that stores the pointer to the previous node, and the next part that stores the pointer to the next node as shown in the below image: The first node also known as HEAD is always used as a reference to traverse the list. Last element contains link to the first element as next and the first element contains link of the last element as previous. A circular doubly linked can be visualized as a chain of nodes, where every node points to previous and next node.
  • 39. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in C UNIT III Structure Declaration struct node { int Element; struct node *FLINK; struct node *BLINK; }; Routine to insert an element at the beginning void Insert_beg(int X, List L) { Position Newnode; Newnode=malloc(sizeof(struct node)); if(Newnode!=NULL) { Newnode→Element = X; Newnode→Flink = L→Flink; L→Flink→Blink = Newnode; L→Flink = Newnode; Newnode →Blink=L; } } Routine to insert an element in the middle void Insert_mid(int X, List L,Position P) { Position Newnode; Newnode=malloc(sizeof(struct node)); if(Newnode!=NULL) { Newnode→Element = X; Newnode→Flink = P→Flink; P→Flink→Blink = Newnode; P→Flink = Newnode; Newnode →Blink=P; } } Routine to insert an element at the last void Insert_last(int X, List L) {
  • 40. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in C UNIT III Position Newnode,P; Newnode=malloc(sizeof(struct node)); if(Newnode!=NULL) { P=L; While(P→Flink!=NULL) P= P→Flink; Newnode→Element = X; P→Flink = Newnode; Newnode→Flink = L; Newnode →Blink=P; L→Blink = Newnode; } } Routine to delete an element from the beginning void dele_first(List L)
  • 41. Sri vidya college of engineering and technology course material { Position Temp; if(L→Flink! = NULL) { Temp= L→Flink ; L→Flink = Temp→Flink; Temp→Flink→Blink = L; free(Temp); } } Routine to delete an element from the middle void dele_mid(int X,List L) { Position P,Temp; P=FindPrevious(X); if(!isLast(P,L) { Temp= P→Flink ; P→Flink = Temp→Flink; Temp→Flink→Blink = P; free(Temp); } } Routine to delete an element from the last void dele_last(List L) { Position Temp; P=L; While(P→Flink!= L) P= P→Flink; Temp= P; P→Blink →Flink = L; L→Blink = P→Blink; free(Temp); } ALGORITHM Case 1: Empty List(start = NULL)  If the list is empty, simply return it. Case 2: The List initially contains some nodes, start points at the first node of the List 1. If the list is not empty, then we define two pointers curr and prev_1 and initialize the pointer curr points to the first node of the list, and prev_1 = NULL.
  • 42. Sri vidya college of engineering and technology course material 2. Traverse the list using the curr pointer to find the node to be deleted and before moving from curr to the next node, every time set prev_1 = curr. 3. If the node is found, check if it is the only node in the list. If yes, set start = NULL and free the node pointing by curr. 4. If the list has more than one node, check if it is the first node of the list. The condition to check this is (curr == start). If yes, then move prev_1 to the last node(prev_1 = start -> prev). After prev_1 reaches the last node, set start = start -> next and prev_1 -> next = start and start -> prev = prev_1. Free the node pointing by curr. 5. If curr is not the first node, we check if it is the last node in the list. The condition to check this is (curr -> next == start). If yes, set prev_1 -> next = start and start -> prev = prev_1. Free the node pointing by curr. 6. If the node to be deleted is neither the first node nor the last node, declare one more pointer temp and initialize the pointer temp points to the next of curr pointer (temp = curr- >next). Now set, prev_1 -> next = temp and temp ->prev = prev_1. Free the node pointing by curr.  If the given key(Say 4) matches with the first node of the list(Step 4):  If the given key(Say 8) matches with the last node of the list(Step 5):
  • 43. Sri vidya college of engineering and technology course material  If the given key(Say 6) matches with the middle node of the list(Step 6): Advantages of Circular Doubly Linked List:  List can be traversed from both directions i.e. from head to tail or from tail to head.  Ease of data manipulation.  Jumping from head to tail or vice versa takes O(1) time. Disadvantages of Circular Doubly Linked List:  Requires additional memory.  More complex than singly linked list.  If not used properly, then the problem of infinite loop can occur. Applications of Circular Doubly Linked List:  Implementation of advanced data structures like Fibonacci Heap.  Used with data where we have to navigate front and back.  Circular doubly linked lists are used in multiprocessing. Real-life applications of Circular Doubly Linked List:  Music Player.  Shopping-cart on online websites.  Browser cache.
  • 44. Sri vidya college of engineering and technology course material Stack ADT  Stack is a specialized data storage structure (Abstract data type).  Unlike arrays, access of elements in a stack is restricted.  It has two main functions o push o pop  Insertion in a stack is done using push function and removal from a stack is done using pop function.  Stack allows access to only the last element inserted hence, an item can be inserted or removed from the stack from one end called the top of the stack. It is therefore, also called Last-In-First-Out (LIFO) list.  Stack has three properties: o capacity stands for the maximum number of elements stack can hold o size stands for the current size of the stack o elements is the array of elements.
  • 45. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in C UNIT III
  • 46. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in C UNIT III 1. createStack function– This function takes the maximum number of elements (maxElements) the stack can hold as an argument, creates a stack according to it and returns a pointer to the stack. It initializes Stack S using malloc function and its properties. 2. push function - This function takes the pointer to the top of the stack S and the item (element) to be inserted as arguments. Check for the emptiness of stack 3. pop function - This function takes the pointer to the top of the stack S as an argument. 4. top function – This function takes the pointer to the top of the stack S as an argumentand returns the topmost element of the stack S. Properties of stacks: 1. Each function runs in O(1) time. 2. It has two basic implementations  Array-based implementation – It is simple and efficient but the maximum size of the stack is fixed.  Singly Linked List-based implementation – It’s complicated but there is no limit on the stack size, it is subjected to the available memory. Stacks - C Program source code #include<stdio.h> #include<stdlib.h> /* Stack has three properties. capacity stands for the maximum number of elements stack can hold. Size stands for the current size of the stack and elements is the array of elements */ typedef struct Stack { int capacity; int size; int *elements; }Stack; /* crateStack function takes argument the maximum number of elements the stack can hold, creates a stack according to it and returns a pointer to the stack. */ Stack * createStack(int maxElements) { /* Create a Stack */ Stack *S; S = (Stack *)malloc(sizeof(Stack)); /* Initialise its properties */ S->elements = (int *)malloc(sizeof(int)*maxElements); S->size = 0; S->capacity = maxElements; /* Return the pointer */ return S; } void pop(Stack *S)
  • 47. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in C UNIT III { /* If stack size is zero then it is empty. So we cannot pop */if(S->size==0) { printf("Stack is Emptyn"); return; } /* Removing an element is equivalent to reducing its size by one */ else { S->size--; } return; } int top(Stack *S) { if(S->size==0) { printf("Stack is Emptyn"); exit(0); } /* Return the topmost element */ return S->elements[S->size-1]; } void push(Stack *S,int element) { /* If the stack is full, we cannot push an element into it as there is no space for it.*/ if(S->size == S->capacity) { } else { } printf("Stack is Fulln"); /* Push an element on the top of it and increase its size by one*/ S->elements[S->size++] = element;
  • 48. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III return; } int main() { Stack *S = createStack(5); push(S,7); push(S,5); push(S,21); push(S,-1); printf("Top element is %dn",top(S)); pop(S); printf("Top element is %dn",top(S)); pop(S); printf("Top element is %dn",top(S)); pop(S); printf("Top element is %dn",top(S)); } Evaluation of Arithmetic Expressions Stacks are useful in evaluation of arithmetic expressions. Consider the expression 5 * 3 +2 + 6 * 4 The expression can be evaluated by first multiplying 5 and 3, storing the result in A, adding 2 and A, saving the result in A. We then multiply 6 and 4 and save the answer in B. We finish off by adding A and B and leaving the final answer in A. A = 15 2 + = 17 B = 6 4 * = 24 A = 17 24 + = 41 We can write this sequence of operations as follows: 5 3 * 2 + 6 4 * + This notation is known as postfix notation and is evaluated as described above. We shall shortly show how this form can be generated using a stack. Basically there are 3 types of notations for expressions. The standard form is known as the infix form. The other two are postfix and prefix forms. Infix: operator is between operands A + B Postfix : operator follows operands A B + Prefix: operator precedes operands + A B Note that all infix expressions can not be evaluated by using the left to right order of the operators inside the expression. However, the operators in a postfix expression are ALWAYS in the correct evaluation order. Thus evaluation of an infix expression is done in two steps. The first step is to convert it into its equivalent postfix expression. The second step involves
  • 49. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III evaluation of the postfix expression. We shall see in this section, how stacks are useful in carrying out both the steps. Let us first examine the basic process of infix to postfix conversion. Infix to postfix conversion: a + b * c Infix form (precedence of * is higher than of +) a + (b * c) convert the multiplication a + ( b c * ) convert the addition a (b c * ) + Remove parentheses a b c * + Postfix form Note that there is no need of parentheses in postfix forms. Example 2: ( A + B ) * C Infix form ( A B + ) * C Convert the addition (A B + ) C * Convert multiplication A B + C * Postfix form No need of parenthesis anywhere Example 3: a + (( b * c ) / d ) 5 a + ( ( b c * ) /d ) (precedence of * and / are same and they are left associative) a + ( b c * d / ) a b c * d / + Queue ADT • It is a linear data structure that maintains a list of elements such that insertion happens at rear end and deletion happens at front end. • FIFO – First In First Out principle Logical Representation of queues:
  • 50. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Queue implementation: • Array implementation of queues • Linked list implementation of queues Array Implementation of queues: Insert operation(Enqueue) • It includes checking whether or not the queue pointer rear is pointing at the upper bound of the array. If it is not, rear is incremented by 1 and the new item is placed at the end of the queue. • Algorithm insert(queue[max],element, front ,rear) Step 1 : Start Step 2 : If front = NULL goto Step 3 else goto Step 6 Step 3 : front = rear = 0 Step 4 : queue[front] = element Step 5 : Goto Step 10 Step 6 : If rear = MAX-1 goto Step 7 else goto Step 8 Step 7 : Display the message,”Queue is FULL” and goto Step 10 Step 8 : rear = rear + 1 Step 9 : queue[rear] = element
  • 51. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Step 10 : Stop
  • 52. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III • Delete operation(Dequeue) – It includes checking whether or not the queue pointer front is already pointing at NULL. . If it is not, the item that is being currently pointed is removed from the queue and front pointer is incremented by 1. – Algorithm delete(queue[MAX], front , rear) Step 1 : Start Step 2 : If front = NULL and rear =NULL goto Step 3 else goto Step 4 Step 3 : Display the message,”Queue is Empty” and goto Step 10 Step 4 : If front != NULL and front = rear goto Step 5 else goto Step 8 Step 5 : Set I = queue[front] Step 6 : Set front = rear = -1 Step 7 : Return the deleted element I and goto Step 10 Step 8 : Set i=queue[front] Step 9 : Return the deleted element i Step 10 : Stop Program to implement queues using arrays: #include<stdio.h> #include<conio.h> #include<stdlib.h> int queue[100]; int front=-1; int rear=-1; void insert(int); int del(); void display(); void main() { int choice; int num1=0,num2=0;
  • 53. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III while(1)
  • 54. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III { case 3: printf(“n Select a choice from the following : “); printf(“n[1] Add an element into the queue”); printf(“n[2] Remove an element from the queue”); printf(“n[3] Display the queue elements”); printf(“n[4] Exitn”); scanf(“%d”,&choice); switch(choice) { case 1: { printf(“nEnter the element to be added :”); scanf(“%d”,&num1); insert(num1); break; } { num2=del(); if(num2==9999); else printf(“n %d element removed from the queue”); getch(); break; } { display(); getch(); break; } Case 4: Exit(1);
  • 55. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III break; default: printf(“nInvalid choice”); break; } } } void display() { int i; if(front==-1) { printf(“Queue is empty”); return; } printf(“n The queue elements are :n”); for(i=front;i<=rear;i++) printf(“t%d”,queue[i]); } void insert(int element) { if(front==-1 ) { front = rear = front +1; queue[front] = element; return; } if(rear==99) {
  • 56. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III printf(“Queue is full”); getch();
  • 57. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III return; } rear = rear +1; queue[rear]=element; } void insert(int element) { if(front==-1 ) { front = rear = front +1; queue[front] = element; return; } if(rear==99) { printf(“Queue is full”); getch(); return; } rear = rear +1; queue[rear]=element; } Linked Implementation of Queues: • It is based on the dynamic memory management techniques which allow allocation and de-allocation of memory space at runtime. Insert operation: It involves the following subtasks : 1. Reserving memory space of the size of a queue element in memory
  • 58. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III 2. Storing the added value at the new location 3. Linking the new element with existing queue 4. Updating the rear pointer
  • 59. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III insert(structure queue, value, front , rear) Step 1: Start Step 2: Set ptr = (struct queue*)malloc(sizeof(struct queue)) Step 3 : Set ptr→element=value Step 4 : if front =NULL goto Step 5 else goto Step 7 Step 5 : Set front =rear = ptr Step 6 : Set ptr→next = NULL and goto Step 10 Step 7 : Set rear→next = ptr Step 8 : Set ptr→next =NULL Step 9 : Set rear = ptr Step 10 : Stop Delete operation: It involves the following subtasks : 1. Checking whether queue is empty 2. Retrieving the front most element of the queue 3. Updating the front pointer 4. Returning the retrieved value delete(structure queue, front , rear) Step 1 : Start Step 2 : if front =NULL goto Step 3 else goto Step 4 Step 3 : Display message, “Queue is empty” and goto Step 7 Step 4 : Set i = front→element Step 5 : Set front = front→next Step 6 : Return the deleted element i Step 7 : Stop Program to implement queues using linked lists: #include<stdio.h> #include<conio.h> #include<stdlib.h>
  • 60. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III struct queue { int element; struct queue *next; }; struct queue *front = NULL; struct queue *rear = NULL; void insert(int); int del(); void display(); void main() { int choice; int num1=0,num2=0; while(1) { printf(“n Select a choice from the following : “); printf(“n[1] Add an element into the queue”); printf(“n[2] Remove an element from the queue”); printf(“n[3] Display the queue elements”); printf(“n[4] Exitn”); scanf(“%d”,&choice); switch(choice) { case 1: { printf(“nEnter the element to be added :”); scanf(“%d”,&num1); insert(num1); break; } case 2:
  • 61. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III { num2=del();
  • 62. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III if(num2==9999) ; else printf(“n %d element removed from the queue”); getch(); break; } case 3: { display(); getch(); break; } case 4: exit(1); break; default: printf(“nInvalid choice”); break; } } } void insert(int element) { struct queue * ptr = (struct queue*)malloc(sizeof(struct queue)); ptr→element=value; if(front =NULL) { front =rear = ptr; ptr→next = NULL; } else {
  • 63. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III rear→ne xt = ptr; ptr→next =NULL; rear = ptr; } } int del() { int i; if(front == NULL) /*checking whether the queue is empty*/ { return(-9999); } else { i = front→ele ment;front = front→ne xt;return i; } } void display() {
  • 64. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III struct queue *ptr = front; if(front==NUL L) { printf(“Queue is empty”);return; } Priority Queue What is a priority queue? A priority queue is an abstract data type that behaves similarly to the normal queue except that each element has some priority, i.e., the element with the highest priority would come first in a priority queue. The priority of the elements in a priority queue will determine the order in which elements are removed from the priority queue. The priority queue supports only comparable elements, which means that the elements are either arranged in an ascending or descending order. For example, suppose we have some values like 1, 3, 4, 8, 14, 22 inserted in a priority queue with an ordering imposed on the values is from least to the greatest. Therefore, the 1 number would be having the highest priority while 22 will be having the lowest priority. Characteristics of a Priority queue  A priority queue is an extension of a queue that contains the following characteristics:  Every element in a priority queue has some priority associated with it.  An element with the higher priority will be deleted before the deletion of the lesser priority.  If two elements in a priority queue have the same priority, they will be arranged using the FIFO principle.
  • 65. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Let's understand the priority queue through an example. We have a priority queue that contains the following values: 1, 3, 4, 8, 14, 22 All the values are arranged in ascending order. Now, we will observe how the priority queue will look after performing the following operations:  poll(): This function will remove the highest priority element from the priority queue. In the above priority queue, the '1' element has the highest priority, so it will be removed from the priority queue.  add(2): This function will insert '2' element in a priority queue. As 2 is the smallest element among all the numbers so it will obtain the highest priority.  poll(): It will remove '2' element from the priority queue as it has the highest priority queue.  add(5): It will insert 5 element after 4 as 5 is larger than 4 and lesser than 8, so it will obtain the third highest priority in a priority queue. Types of Priority Queue There are two types of priority queue: Ascending order priority queue: In ascending order priority queue, a lower priority number is given as a higher priority in a priority. For example, we take the numbers from 1 to 5 arranged in an ascending order like 1,2,3,4,5; therefore, the smallest number, i.e., 1 is given as the highest priority in a priority queue.
  • 66. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Descending order priority queue: In descending order priority queue, a higher priority number is given as a higher priority in a priority. For example, we take the numbers from 1 to 5 arranged in descending order like 5, 4, 3, 2, 1; therefore, the largest number, i.e., 5 is given as the highest priority in a priority queue. Representation of priority queue Now, we will see how to represent the priority queue through a one-way list. We will create the priority queue by using the list given below in which INFO list contains the data elements, PRN list contains the priority numbers of each data element available in the INFO list, and LINK basically contains the address of the next node. Let's create the priority queue step by step. In the case of priority queue, lower priority number is considered the higher priority, i.e., lower priority number = higher priority. Step 1: In the list, lower priority number is 1, whose data value is 333, so it will be inserted in the list as shown in the below diagram:
  • 67. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Step 2: After inserting 333, priority number 2 is having a higher priority, and data values associated with this priority are 222 and 111. So, this data will be inserted based on the FIFO principle; therefore 222 will be added first and then 111. Step 3: After inserting the elements of priority 2, the next higher priority number is 4 and data elements associated with 4 priority numbers are 444, 555, 777. In this case, elements would be inserted based on the FIFO principle; therefore, 444 will be added first, then 555, and then 777. Step 4: After inserting the elements of priority 4, the next higher priority number is 5, and the value associated with priority 5 is 666, so it will be inserted at the end of the queue. Implementation of Priority Queue The priority queue can be implemented in four ways that include arrays, linked list, heap data structure and binary search tree. The heap data structure is the most efficient way of implementing the priority queue, so we will implement the priority queue using a heap data structure in this topic. Now, first we understand the reason why heap is the most efficient way among all the other data structures. Analysis of complexities using different implementations Implementation add Remove peek Linked list O(1) O(n) O(n) Binary heap O(logn) O(logn) O(1) Binary search tree O(logn) O(logn) O(1) What is Heap? A heap is a tree-based data structure that forms a complete binary tree, and satisfies the heap property. If A is a parent node of B, then A is ordered with respect to the node B for all nodes A and B in a heap. It means that the value of the parent node could be more than or equal to the value of the child node, or the value of the parent node could be less than or equal to the value of the child node. Therefore, we can say that there are two types of heaps:
  • 68. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Max heap: The max heap is a heap in which the value of the parent node is greater than the value of the child nodes. Min heap: The min heap is a heap in which the value of the parent node is less than the value of the child nodes. Both the heaps are the binary heap, as each has exactly two child nodes. Priority Queue Operations The common operations that we can perform on a priority queue are insertion, deletion and peek. Let's see how we can maintain the heap data structure. Inserting the element in a priority queue (max heap) If we insert an element in a priority queue, it will move to the empty slot by looking from top to bottom and left to right.
  • 69. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III If the element is not in a correct place then it is compared with the parent node; if it is found out of order, elements are swapped. This process continues until the element is placed in a correct position. Heapify, Removing the minimum element from the priority queue As we know that in a max heap, the maximum element is the root node. When we remove the root node, it creates an empty slot. The last inserted element will be added in this empty slot. Then, this element is compared with the child nodes, i.e., left-child and right child, and swap with the smaller of the two. It keeps moving down the tree until the heap property is restored. Applications of Priority queue The following are the applications of the priority queue:  It is used in the Dijkstra's shortest path algorithm.  It is used in prim's algorithm  It is used in data compression techniques like Huffman code.
  • 70. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III  It is used in heap sort.  It is also used in operating system like priority scheduling, load balancing and interrupt handling. Program to create the priority queue using the binary max heap. #include <stdio.h> #include <stdio.h> int heap[40]; int size=-1; // retrieving the parent node of the child node int parent(int i) { return (i - 1) / 2; } // retrieving the left child of the parent node. int left_child(int i) { return i+1; } // retrieving the right child of the parent int right_child(int i) { return i+2; } // Returning the element having the highest priority int get_Max()
  • 71. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III { return heap[0]; } //Returning the element having the minimum priority int get_Min() { return heap[size]; } // function to move the node up the tree in order to restore the heap property. void moveUp(int i) { while (i > 0) { // swapping parent node with a child node if(heap[parent(i)] < heap[i]) { int temp; temp=heap[parent(i)]; heap[parent(i)]=heap[i]; heap[i]=temp; } // updating the value of i to i/2 i=i/2; } } //function to move the node down the tree in order to restore the heap property.
  • 72. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III void moveDown(int k) { int index = k; // getting the location of the Left Child int left = left_child(k); if (left <= size && heap[left] > heap[index]) { index = left; } // getting the location of the Right Child int right = right_child(k); if (right <= size && heap[right] > heap[index]) { index = right; } // If k is not equal to index if (k != index) { int temp; temp=heap[index]; heap[index]=heap[k]; heap[k]=temp; moveDown(index); } } // Removing the element of maximum priority void removeMax()
  • 73. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III { int r= heap[0]; heap[0]=heap[size]; size=size-1; moveDown(0); } //inserting the element in a priority queue void insert(int p) { size = size + 1; heap[size] = p; // move Up to maintain heap property moveUp(size); } //Removing the element from the priority queue at a given index i. void delete(int i) { heap[i] = heap[0] + 1; // move the node stored at ith location is shifted to the root node moveUp(i); // Removing the node having maximum priority removeMax(); } int main() {
  • 74. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III // Inserting the elements in a priority queue insert(20); insert(19); insert(21); insert(18); insert(12); insert(17); insert(15); insert(16); insert(14); int i=0; printf("Elements in a priority queue are : "); for(int i=0;i<=size;i++) { printf("%d ",heap[i]); } delete(2); // deleting the element whose index is 2. printf("nElements in a priority queue after deleting the element are : "); for(int i=0;i<=size;i++) { printf("%d ",heap[i]); } int max=get_Max(); printf("nThe element which is having the highest priority is %d: ",max);
  • 75. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III int min=get_Min(); printf("nThe element which is having the minimum priority is : %d",min); return 0; } In the above program, we have created the following functions: int parent(int i): This function returns the index of the parent node of a child node, i.e., i. int left_child(int i): This function returns the index of the left child of a given index, i.e., i. int right_child(int i): This function returns the index of the right child of a given index, i.e., i. void moveUp(int i): This function will keep moving the node up the tree until the heap property is restored. void moveDown(int i): This function will keep moving the node down the tree until the heap property is restored. void removeMax(): This function removes the element which is having the highest priority. void insert(int p): It inserts the element in a priority queue which is passed as an argument in a function. void delete(int i): It deletes the element from a priority queue at a given index. int get_Max(): It returns the element which is having the highest priority, and we know that in max heap, the root node contains the element which has the largest value, and highest priority. int get_Min(): It returns the element which is having the minimum priority, and we know that in max heap, the last node contains the element which has the smallest value, and lowest priority.
  • 76. Sri vidya college of engineering and technology course material EC8393/fundamentals of data structures in UNIT III Output