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

DS_Tree_Notes

Data Structures Tree Notes

Uploaded by

vijethadc.gpm
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

DS_Tree_Notes

Data Structures Tree Notes

Uploaded by

vijethadc.gpm
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

1|Page

Linked List:
A linked list is a linear data structure which can store a collection of "nodes"
connected together via links i.e. pointers. Linked lists nodes are not stored at a
contiguous location, rather they are linked using pointers to the different
memory locations. A node consists of the data value and a pointer to the
address of the next node within the linked list.
A linked list is a dynamic linear data structure whose memory size can be
allocated or de-allocated at run time based on the operation insertion or
deletion, this helps in using system memory efficiently. Linked lists can be used
to implement various data structures like a stack, queue, graph, hash maps,
etc.

A linked list starts with a head node which points to the first node. Every node
consists of data which holds the actual data (value) associated with the node
and a next pointer which holds the memory address of the next node in the
linked list. The last node is called the tail node in the list which points
to null indicating the end of the list.
Why use linked list over array?
Linked list is a data structure that overcomes the limitations of arrays. Let's first
see some of the limitations of arrays -
 The size of the array must be known in advance before using it in the
program.
 Increasing the size of the array is a time taking process. It is almost
impossible to expand the size of the array at run time.
 All the elements in the array need to be contiguously stored in the
memory. Inserting an element in the array needs shifting of all its
predecessors.
 Linked list is useful because -
 It allocates the memory dynamically. All the nodes of the linked list are
non-contiguously stored in the memory and linked together with the help
of pointers.
 In linked list, size is no longer a problem since we do not need to define its
size at the time of declaration. List grows as per the program's demand
and limited to the available memory space.
Declaring a Linked List
It is simple to declare an array, as it is of single type, while the declaration of
linked list is a bit more typical than array. Linked list contains two parts, and
both are of different types, i.e., one is the simple variable, while another is the
pointer variable. We can declare the linked list by using the user-defined data
type structure.
The declaration of linked list is given as follows -
Page | 1
2|Page

struct node
{
int data;
struct node *next;
}
In the above declaration, we have defined a structure named as node that
contains two variables, one is data that is of integer type, and another one
is next that is a pointer which contains the address of next node.

Types of Linked list


Linked list is classified into the following types -
Singly Linked list
It is the commonly used linked list in programs. If we are talking about the linked list, it means it is a singly linked list.
The singly linked list is a data structure that contains two parts, i.e., one is the data part, and the other one is the
address part, which contains the address of the next or the successor node. The address part in a node is also known
as a pointer.

We can observe in the above figure that there are three different nodes having address 100, 200 and 300
respectively. The first node contains the address of the next node, i.e., 200, the second node contains the address of
the last node, i.e., 300, and the third node contains the NULL value in its address part as it does not point to any
node. The pointer that holds the address of the initial node is known as a head pointer.
The linked list, which is shown in the above diagram, is known as a singly linked list as it contains only a single link. In
this list, only forward traversal is possible; we cannot traverse in the backward direction as it has only one link in the
list.
Representation of the node in a singly linked list
struct node
{
int data;
struct node *next;
}
In the above representation, we have defined a user-defined structure named a node containing two members, the
first one is data of integer type, and the other one is the pointer (next) of the node type.
Doubly linked list
As the name suggests, the doubly linked list contains two pointers. We can define the doubly linked list as a linear
data structure with three parts: the data part and the other two address part. In other words, a doubly linked list is a
list that has three parts in a single node, includes one data part, a pointer to its previous node, and a pointer to the
next node.
Suppose we have three nodes, and the address of these nodes are 100, 200 and 300, respectively. The
representation of these nodes in a doubly-linked list is shown below:

Page | 2
3|Page

As we can observe in the above figure, the node in a doubly-linked list has two address parts; one part stores
the address of the next while the other part of the node stores the previous node's address. The initial node in the
doubly linked list has the NULL value in the address part, which provides the address of the previous node.

Representation of the node in a doubly linked list


struct node
{
int data;
struct node *next;
struct node *prev;
}
In the above representation, we have defined a user-defined structure named a node with three members, one
is data of integer type, and the other two are the pointers, i.e., next and prev of the node type. The next
pointer variable holds the address of the next node, and the prev pointer holds the address of the previous node.
The type of both the pointers, i.e., next and prev is struct node as both the pointers are storing the address of the
node of the struct node type.
Circular linked list
A circular linked list is a variation of a singly linked list. The only difference between the singly linked list and
a circular linked list is that the last node does not point to any node in a singly linked list, so its link part contains a
NULL value. On the other hand, the circular linked list is a list in which the last node connects to the first node, so the
link part of the last node holds the first node's address. The circular linked list has no starting and ending node. We
can traverse in any direction, i.e., either backward or forward. The diagrammatic representation of the circular linked
list is shown below:
struct node
{
int data;
struct node *next;
}
A circular linked list is a sequence of elements in which each node has a link to the next node, and the last node is
having a link to the first node. The representation of the circular linked list will be similar to the singly linked list, as
shown below:

Page | 3
4|Page

Doubly Circular linked list


The doubly circular linked list has the features of both the circular linked list and doubly linked list.

The above figure shows the representation of the doubly circular linked list in which the last node is attached to the
first node and thus creates a circle. It is a doubly linked list also because each node holds the address of the previous
node also. The main difference between the doubly linked list and doubly circular linked list is that the doubly
circular linked list does not contain the NULL value in the previous field of the node. As the doubly circular linked
contains three parts, i.e., two address parts and one data part so its representation is similar to the doubly linked list.
struct node
{
int data;
struct node *next;
struct node *prev;
}
Advantages of linked lists
1) The primary advantage of linked list over arrays is that linked list can
increase and decrease in size. That means their maximum size need not be
mentioned in advance. This is a very good advantage in practical applications.
2) The second advantage of linked list is the flexibility in allowing the items to
the rearranged efficiently. This flexibility is gained at the experience of quick
access to any item in this.
3) The insertion and deletion of an element takes one time. Unlike array
implementation in which they take n-times.
Limitations of linked lists:
1) The space needed to store a list using more.
2) Another limitation is that it is not possible to travel a list in both directions.
This can be overcome in double linked list.
Differences between arrays & linked lists:
Arrays Linked List
1. Array is fixed in size. 1. No. of nodes in the list is unlimited.
2. Static allocation of memory is 2. Dynamic Memory allocation is done.
done.
3. Use initialized area. 3. Uses free store or heap memory
area.
4. Only identical items can be placed. 4. Identical or different items may be
placed.
5. Optimum utilization of memory will 5. Optimum utilization of memory is
not be found. done.
6. Do not use pointers concept. 6. Uses pointers only.
7. Continuous blocks of memory is 7. Doesn’t need continuous memory.
Page | 4
5|Page

required.
BASIC OPERATIONS ON SINGLE LINKED LISTS
Creating a Linked List:
The creation of a list is the most basic operation among other operations.
Algorithm: Creation( )
[ Initially head = null and last = null ]
Step-1: Read a value into item
Step-2: if(item = = -1) then
[ end the process ]
Else
Step-2.1 :
create a new node called “temp”
Step-2.2 : Insert temp.data = item , temp.link = null.
Step-2.3 : if head = = null then
head = last = temp
else
last.link = temp
last = temp
[ Repeat the process until item = -1 ]
Step-3: Exit

Insertion
In a single linked list, the insertion operation can be performed in three ways.
They are as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Inserting At Beginning of the list
We can use the following steps to insert a new node at beginning of the single
linked list...
 Step 1 - Create a newNode with given value.
 Step 2 - Check whether list is Empty (head == NULL)
 Step 3 - If it is Empty then,
set newNode→next = NULL and head = newNode.
 Step 4 - If it is Not Empty then,
set newNode→next = head and head = newNode.
void insertAtBeginning(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(head == NULL)
{
newNode->next = NULL;
head = newNode;
}
else
{
newNode->next = head;
head = newNode;

Page | 5
6|Page

}
printf("\nOne node inserted!!!\n");
}
Inserting At End of the list
We can use the following steps to insert a new node at end of the single linked
list...
 Step 1 - Create a newNode with given value and newNode →
next as NULL.
 Step 2 - Check whether list is Empty (head == NULL).
 Step 3 - If it is Empty then, set head = newNode.
 Step 4 - If it is Not Empty then, define a node pointer temp and
initialize with head.
 Step 5 - Keep moving the temp to its next node until it reaches to the
last node in the list (until temp → next is equal to NULL).
 Step 6 - Set temp → next = newNode.
void insertAtEnd(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if(head == NULL)
head = newNode;
else
{
struct Node *temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
printf("\nOne node inserted!!!\n");
}
Inserting At Specific location in the list (After a Node)
We can use the following steps to insert a new node after a node in the single
linked list...
 Step 1 - Create a newNode with given value.
 Step 2 - Check whether list is Empty (head == NULL)
 Step 3 - If it is Empty then, set newNode →
next = NULL and head = newNode.
 Step 4 - If it is Not Empty then, define a node pointer temp and
initialize with head.
 Step 5 - Keep moving the temp to its next node until it reaches to the
node after which we want to insert the newNode (until temp1 → data is
equal to location, here location is the node value after which we want to
insert the newNode).
 Step 6 - Every time check whether temp is reached to last node or not. If
it is reached to last node then display 'Given node is not found in the
list!!! Insertion not possible!!!' and terminate the function. Otherwise
move the temp to next node.
 Step 7 - Finally, Set 'newNode → next = temp → next' and 'temp →
next = newNode'
void insertBetween(int value, int loc1, int loc2)
{

Page | 6
7|Page

struct Node *newNode;


newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(head == NULL)
{
newNode->next = NULL;
head = newNode;
}
else
{
struct Node *temp = head;
while(temp->data != loc1 && temp->data != loc2)
temp = temp->next;
newNode->next = temp->next;
temp->next = newNode;
}
printf("\nOne node inserted!!!\n");
}
Deletion
In a single linked list, the deletion operation can be performed in three ways.
They are as follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node
Deleting from Beginning of the list
We can use the following steps to delete a node from beginning of the single
linked list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
 Step 3 - If it is Not Empty then, define a Node pointer 'temp' and
initialize with head.
 Step 4 - Check whether list is having only one node (temp →
next == NULL)
 Step 5 - If it is TRUE then set head = NULL and
delete temp (Setting Empty list conditions)
 Step 6 - If it is FALSE then set head = temp → next, and delete temp.
void removeBeginning()
{
if(head == NULL)
printf("\n\nList is Empty!!!");
else
{
struct Node *temp = head;
if(head->next == NULL)
{
head = NULL;
free(temp);
}
else
{
head = temp->next;
free(temp);
printf("\nOne node deleted!!!\n\n");
}
}
}
Page | 7
8|Page

Deleting from End of the list


We can use the following steps to delete a node from end of the single linked
list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
 Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and
'temp2' and initialize 'temp1' with head.
 Step 4 - Check whether list has only one Node (temp1 →
next == NULL)
 Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And
terminate the function. (Setting Empty list condition)
 Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to
its next node. Repeat the same until it reaches to the last node in the list.
(until temp1 → next == NULL)
 Step 7 - Finally, Set temp2 → next = NULL and delete temp1.
void removeEnd()
{
if(head == NULL)
{
printf("\nList is Empty!!!\n");
}
else
{
struct Node *temp1 = head,*temp2;
if(head->next == NULL)
head = NULL;
else
{
while(temp1->next != NULL)
{
temp2 = temp1;
temp1 = temp1->next;
}
temp2->next = NULL;
}
free(temp1);
printf("\nOne node deleted!!!\n\n");
}
}
Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the single linked
list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
 Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and
'temp2' and initialize 'temp1' with head.
 Step 4 - Keep moving the temp1 until it reaches to the exact node to be
deleted or to the last node. And every time set 'temp2 = temp1' before
moving the 'temp1' to its next node.
 Step 5 - If it is reached to the last node then display 'Given node not
found in the list! Deletion not possible!!!'. And terminate the
function.
Page | 8
9|Page

 Step 6 - If it is reached to the exact node which we want to delete, then


check whether list is having only one node or not
 Step 7 - If list has only one node and that is the node to be deleted, then
set head = NULL and delete temp1 (free(temp1)).
 Step 8 - If list contains multiple nodes, then check whether temp1 is the
first node in the list (temp1 == head).
 Step 9 - If temp1 is the first node then move the head to the next node
(head = head → next) and delete temp1.
 Step 10 - If temp1 is not first node then check whether it is last node in
the list (temp1 → next == NULL).
 Step 11 - If temp1 is last node then set temp2 → next = NULL and
delete temp1 (free(temp1)).
 Step 12 - If temp1 is not first node and not last node then set temp2 →
next = temp1 → next and delete temp1 (free(temp1)).
void removeSpecific(int delValue)
{
struct Node *temp1 = head, *temp2;
while(temp1->data != delValue)
{
if(temp1 -> next == NULL){
printf("\nGiven node not found in the list!!!");
goto functionEnd;
}
temp2 = temp1;
temp1 = temp1 -> next;
}
temp2 -> next = temp1 -> next;
free(temp1);
printf("\nOne node deleted!!!\n\n");
functionEnd:
}
Displaying a Single Linked List
We can use the following steps to display the elements of a single linked list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty then, display 'List is Empty!!!' and terminate the
function.
 Step 3 - If it is Not Empty then, define a Node pointer 'temp' and
initialize with head.
 Step 4 - Keep displaying temp → data with an arrow (--->)
until temp reaches to the last node
 Step 5 - Finally display temp → data with arrow pointing to NULL (temp
→ data ---> NULL).
void display()
{
if(head == NULL)
{
printf("\nList is Empty\n");
}
else
{
struct Node *temp = head;
printf("\n\nList elements are - \n");
while(temp->next != NULL)
{
printf("%d --->",temp->data);
Page | 9
10 | P a g e

temp = temp->next;
}
printf("%d --->NULL",temp->data);
}
}

Applications of linked list in computer science:


1. Implementation of stacks and queues
2. Implementation of graphs: Adjacency list representation of graphs is the
most popular which uses a linked list to store adjacent vertices.
3. Dynamic memory allocation: We use a linked list of free blocks.
4. Maintaining a directory of names
5. Performing arithmetic operations on long integers
6. Manipulation of polynomials by storing constants in the node of the linked
list
7. Representing sparse matrices
Applications of linked list in the real world:
1. Image viewer – Previous and next images are linked and can be accessed
by the next and previous buttons.
2. Previous and next page in a web browser – We can access the previous
and next URL searched in a web browser by pressing the back and next
buttons since they are linked as a linked list.
3. Music Player – Songs in the music player are linked to the previous and
next songs. So you can play songs either from starting or ending of the
list.
4. GPS navigation systems- Linked lists can be used to store and manage a
list of locations and routes, allowing users to easily navigate to their
desired destination.
5. Robotics- Linked lists can be used to implement control systems for
robots, allowing them to navigate and interact with their environment.
6. Task Scheduling- Operating systems use linked lists to manage task
scheduling, where each process waiting to be executed is represented as
a node in the list.
7. Image Processing- Linked lists can be used to represent images, where
each pixel is represented as a node in the list.
8. File Systems- File systems use linked lists to represent the hierarchical
structure of directories, where each directory or file is represented as a
node in the list.
9. Symbol Table- Compilers use linked lists to build a symbol table, which is a
data structure that stores information about identifiers used in a program.
10. Undo/Redo Functionality- Many software applications implement
undo/redo functionality using linked lists, where each action that can be
undone is represented as a node in a doubly linked list.
11. Speech Recognition- Speech recognition software uses linked lists to
represent the possible phonetic pronunciations of a word, where each
possible pronunciation is represented as a node in the list.
12. Polynomial Representation- Polynomials can be represented using
linked lists, where each term in the polynomial is represented as a node in
the list.
Page | 10
11 | P a g e

13. Simulation of Physical Systems- Linked lists can be used to simulate


physical systems, where each element in the list represents a discrete
point in time and the state of the system at that time.
Circular Linked List
Circular Linked List:
In single linked list, every node points to its next node in the sequence and the
last node points NULL. But in circular linked list, every node points to its next
node in the sequence but the last node points to the first node in the list.
Circular linked list is a sequence of elements in which every element has link to
its next element in the sequence and the last element has a link to the first
element in the sequence.
That means circular linked list is similar to the single linked list except that the
last node points to the first node in the list
Example

Operations
In a circular linked list, we perform the following operations...
1. Insertion
2. Deletion
3. Display
Before we implement actual operations, first we need to setup empty list. First
perform the following steps before implementing actual operations.
 Step 1 - Include all the header files which are used in the program.
 Step 2 - Declare all the user defined functions.
 Step 3 - Define a Node structure with two members data and next
 Step 4 - Define a Node pointer 'head' and set it to NULL.
 Step 5 - Implement the main method by displaying operations menu and
make suitable function calls in the main method to perform user selected
operation.
Insertion
In a circular linked list, the insertion operation can be performed in three ways.
They are as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Inserting At Beginning of the list
We can use the following steps to insert a new node at beginning of the circular
linked list...
 Step 1 - Create a newNode with given value.
 Step 2 - Check whether list is Empty (head == NULL)
 Step 3 - If it is Empty then,
set head = newNode and newNode→next = head .
Page | 11
12 | P a g e

 Step 4 - If it is Not Empty then, define a Node pointer 'temp' and


initialize with 'head'.
 Step 5 - Keep moving the 'temp' to its next node until it reaches to the
last node (until 'temp → next == head').
 Step 6 - Set 'newNode → next =head', 'head = newNode' and 'temp
→ next = head'.
Inserting At End of the list
We can use the following steps to insert a new node at end of the circular
linked list...
 Step 1 - Create a newNode with given value.
 Step 2 - Check whether list is Empty (head == NULL).
 Step 3 - If it is Empty then, set head = newNode and newNode →
next = head.
 Step 4 - If it is Not Empty then, define a node pointer temp and
initialize with head.
 Step 5 - Keep moving the temp to its next node until it reaches to the
last node in the list (until temp → next == head).
 Step 6 - Set temp → next = newNode and newNode → next = head.
Inserting At Specific location in the list (After a Node)
We can use the following steps to insert a new node after a node in the circular
linked list...
 Step 1 - Create a newNode with given value.
 Step 2 - Check whether list is Empty (head == NULL)
 Step 3 - If it is Empty then, set head = newNode and newNode →
next = head.
 Step 4 - If it is Not Empty then, define a node pointer temp and
initialize with head.
 Step 5 - Keep moving the temp to its next node until it reaches to the
node after which we want to insert the newNode (until temp1 → data is
equal to location, here location is the node value after which we want to
insert the newNode).
 Step 6 - Every time check whether temp is reached to the last node or
not. If it is reached to last node then display 'Given node is not found
in the list!!! Insertion not possible!!!' and terminate the function.
Otherwise move the temp to next node.
 Step 7 - If temp is reached to the exact node after which we want to
insert the newNode then check whether it is last node (temp → next ==
head).
 Step 8 - If temp is last node then set temp →
next = newNode and newNode → next = head.
 Step 8 - If temp is not last node then set newNode → next = temp →
next and temp → next = newNode.
Deletion
In a circular linked list, the deletion operation can be performed in three ways
those are as follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node
Page | 12
13 | P a g e

Deleting from Beginning of the list


We can use the following steps to delete a node from beginning of the circular
linked list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
 Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and
'temp2' and initialize both 'temp1' and 'temp2' with head.
 Step 4 - Check whether list is having only one node (temp1 →
next == head)
 Step 5 - If it is TRUE then set head = NULL and
delete temp1 (Setting Empty list conditions)
 Step 6 - If it is FALSE move the temp1 until it reaches to the last node.
(until temp1 → next == head )
 Step 7 - Then set head = temp2 → next, temp1 → next = head and
delete temp2.
Deleting from End of the list
We can use the following steps to delete a node from end of the circular linked
list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
 Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and
'temp2' and initialize 'temp1' with head.
 Step 4 - Check whether list has only one Node (temp1 →
next == head)
 Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And
terminate from the function. (Setting Empty list condition)
 Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to
its next node. Repeat the same until temp1 reaches to the last node in
the list. (until temp1 → next == head)
 Step 7 - Set temp2 → next = head and delete temp1.
Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the circular linked
list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
 Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and
'temp2' and initialize 'temp1' with head.
 Step 4 - Keep moving the temp1 until it reaches to the exact node to be
deleted or to the last node. And every time set 'temp2 = temp1' before
moving the 'temp1' to its next node.
 Step 5 - If it is reached to the last node then display 'Given node not
found in the list! Deletion not possible!!!'. And terminate the
function.
 Step 6 - If it is reached to the exact node which we want to delete, then
check whether list is having only one node (temp1 → next == head)
Page | 13
14 | P a g e

 Step 7 - If list has only one node and that is the node to be deleted then
set head = NULL and delete temp1 (free(temp1)).
 Step 8 - If list contains multiple nodes then check whether temp1 is the
first node in the list (temp1 == head).
 Step 9 - If temp1 is the first node then set temp2 = head and keep
moving temp2 to its next node until temp2 reaches to the last node.
Then set head = head → next, temp2 → next = head and
delete temp1.
 Step 10 - If temp1 is not first node then check whether it is last node in
the list (temp1 → next == head).
 Step 1 1- If temp1 is last node then set temp2 → next = head and
delete temp1 (free(temp1)).
 Step 12 - If temp1 is not first node and not last node then set temp2 →
next = temp1 → next and delete temp1(free(temp1)).
Displaying a circular Linked List
We can use the following steps to display the elements of a circular linked list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the
function.
 Step 3 - If it is Not Empty then, define a Node pointer 'temp' and
initialize with head.
 Step 4 - Keep displaying temp → data with an arrow (--->)
until temp reaches to the last node
 Step 5 - Finally display temp → data with arrow pointing to head →
data.
Double Linked List
What is Double Linked List?
In a single linked list, every node has link to its next node in the sequence. So,
we can traverse from one node to other node only in one direction and we can
not traverse back. We can solve this kind of problem by using double linked list.
Double linked list can be defined as follows...
Double linked list is a sequence of elements in which every element
has links to its previous element and next element in the sequence.
In double linked list, every node has link to its previous node and next node. So,
we can traverse forward by using next field and can traverse backward by
using previous field. Every node in a double linked list contains three fields and
they are shown in the following figure...

Here, 'link1' field is used to store the address of the previous node in the
sequence, 'link2' field is used to store the address of the next node in the
sequence and 'data' field is used to store the actual value of that node.
Example

Page | 14
15 | P a g e

Important Points to be Remembered


In double linked list, the first node must be always pointed by head.
Always the previous field of the first node must be NULL.
Always the next field of the last node must be NULL.
Operations on Double Linked List
In a double linked list, we perform the following operations...
1. Insertion
2. Deletion
3. Display
Insertion
In a double linked list, the insertion operation can be performed in three ways
as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Inserting At Beginning of the list
We can use the following steps to insert a new node at beginning of the double
linked list...
 Step 1 - Create a newNode with given value and newNode →
previous as NULL.
 Step 2 - Check whether list is Empty (head == NULL)
 Step 3 - If it is Empty then, assign NULL to newNode →
next and newNode to head.
 Step 4 - If it is not Empty then, assign head to newNode →
next and newNode to head.
Inserting At End of the list
We can use the following steps to insert a new node at end of the double linked
list...
 Step 1 - Create a newNode with given value and newNode →
next as NULL.
 Step 2 - Check whether list is Empty (head == NULL)
 Step 3 - If it is Empty, then assign NULL to newNode →
previous and newNode to head.
 Step 4 - If it is not Empty, then, define a node pointer temp and
initialize with head.
 Step 5 - Keep moving the temp to its next node until it reaches to the
last node in the list (until temp → next is equal to NULL).
 Step 6 - Assign newNode to temp → next and temp to newNode →
previous.
Inserting At Specific location in the list (After a Node)
We can use the following steps to insert a new node after a node in the double
linked list...

Page | 15
16 | P a g e

 Step 1 - Create a newNode with given value.


 Step 2 - Check whether list is Empty (head == NULL)
 Step 3 - If it is Empty then, assign NULL to both newNode →
previous & newNode → next and set newNode to head.
 Step 4 - If it is not Empty then, define two node
pointers temp1 & temp2 and initialize temp1 with head.
 Step 5 - Keep moving the temp1 to its next node until it reaches to the
node after which we want to insert the newNode (until temp1 → data is
equal to location, here location is the node value after which we want to
insert the newNode).
 Step 6 - Every time check whether temp1 is reached to the last node. If
it is reached to the last node then display 'Given node is not found in
the list!!! Insertion not possible!!!' and terminate the function.
Otherwise move the temp1 to next node.
 Step 7 - Assign temp1 → next to temp2, newNode to temp1 →
next, temp1 to newNode → previous, temp2 to newNode →
next and newNode to temp2 → previous.
Deletion
In a double linked list, the deletion operation can be performed in three ways
as follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node
Deleting from Beginning of the list
We can use the following steps to delete a node from beginning of the double
linked list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
 Step 3 - If it is not Empty then, define a Node pointer 'temp' and
initialize with head.
 Step 4 - Check whether list is having only one node (temp →
previous is equal to temp → next)
 Step 5 - If it is TRUE, then set head to NULL and
delete temp (Setting Empty list conditions)
 Step 6 - If it is FALSE, then assign temp →
next to head, NULL to head → previous and delete temp.
Deleting from End of the list
We can use the following steps to delete a node from end of the double linked
list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty, then display 'List is Empty!!! Deletion is not
possible' and terminate the function.
 Step 3 - If it is not Empty then, define a Node pointer 'temp' and
initialize with head.
 Step 4 - Check whether list has only one Node (temp →
previous and temp → next both are NULL)

Page | 16
17 | P a g e

 Step 5 - If it is TRUE, then assign NULL to head and delete temp. And
terminate from the function. (Setting Empty list condition)
 Step 6 - If it is FALSE, then keep moving temp until it reaches to the last
node in the list. (until temp → next is equal to NULL)
 Step 7 - Assign NULL to temp → previous → next and delete temp.
Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the double linked
list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
 Step 3 - If it is not Empty, then define a Node pointer 'temp' and
initialize with head.
 Step 4 - Keep moving the temp until it reaches to the exact node to be
deleted or to the last node.
 Step 5 - If it is reached to the last node, then display 'Given node not
found in the list! Deletion not possible!!!' and terminate the fuction.
 Step 6 - If it is reached to the exact node which we want to delete, then
check whether list is having only one node or not
 Step 7 - If list has only one node and that is the node which is to be
deleted then set head to NULL and delete temp(free(temp)).
 Step 8 - If list contains multiple nodes, then check whether temp is the
first node in the list (temp == head).
 Step 9 - If temp is the first node, then move the head to the next node
(head = head → next), set head of previous to NULL (head →
previous = NULL) and delete temp.
 Step 10 - If temp is not the first node, then check whether it is the last
node in the list (temp → next == NULL).
 Step 11 - If temp is the last node then
set temp of previous of next to NULL (temp → previous → next =
NULL) and delete temp (free(temp)).
 Step 12 - If temp is not the first node and not the last node, then
set temp of previous of next to temp of next (temp → previous →
next = temp →
next), temp of next of previous to temp of previous (temp → next →
previous = temp → previous) and delete temp (free(temp)).
Displaying a Double Linked List
We can use the following steps to display the elements of a double linked list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the
function.
 Step 3 - If it is not Empty, then define a Node pointer 'temp' and
initialize with head.
 Step 4 - Display 'NULL <--- '.
 Step 5 - Keep displaying temp → data with an arrow (<===>)
until temp reaches to the last node
 Step 6 - Finally, display temp → data with arrow pointing
to NULL (temp → data ---> NULL).
Page | 17
18 | P a g e

Circular Doubly Linked List


A circular doubly linked list is a special kind of list used in Data Structure to
store data. In this list, each piece of data is stored in a node. Every node is
connected to two other nodes: one before it and one after it. This makes it easy
to move forwards and backwards through the list.
What's unique about a circular doubly linked list is that the last node connects
back to the first node, forming a circle. So, if you start at any node and keep
moving forwards or backwards, you will eventually come back to the starting
node.
This circular connection makes it different from regular linked lists, where the
last node simply points to nothing (or "null").

Example:
Imagine a circular doubly linked list like a Ferris wheel. Each node is like a seat
on the Ferris wheel. You can move to the seat next to you (forward) or the seat
behind you (backward). And when you reach the last seat, instead of stopping,
you move to the first seat again, just like how the Ferris wheel goes round and
round.
This structure is useful in many computer applications where you need to cycle
through data repeatedly, such as in task scheduling or managing playlists in a
media player.

Structure of Circular Doubly Linked List


A circular doubly linked list is made up of nodes, where each node has three
main components: data, a next pointer, and a previous pointer.
Nodes and Their Components
 Data: This is the actual information or value stored in the node.
 Next Pointer: This pointer points to the next node in the list.
 Previous Pointer: This pointer points to the previous node in the list.
Circular Nature
 In a circular doubly linked list, the next pointer of the last node points to
the first node, creating a circular loop.
 Similarly, the previous pointer of the first node points to the last node,
allowing bidirectional traversal in a circular manner.

Page | 18
19 | P a g e

Basic Operations on Circular Doubly Linked List


1. Insertion
Inserting at the Beginning:
 Create a new node.
 Adjust the next pointer of the new node to point to the head.
 Adjust the previous pointer of the head to point to the new node.
 Set the new node as the new head.
 Update the previous pointer of the new head to point to the last node, and
the next pointer of the last node to point to the new head.
Inserting at the End:
 Create a new node.
 Adjust the previous pointer of the new node to point to the last node.
 Adjust the next pointer of the last node to point to the new node.
 Set the next pointer of the new node to point to the head.
 Update the previous pointer of the head to point to the new node.
Inserting at a Given Position:
 Traverse the list to find the position.
 Adjust the pointers of the new node and the nodes at the position to
insert the new node.
2. Deletion
Deleting from the Beginning:
 Adjust the next pointer of the last node to point to the second node.
 Set the second node as the new head.
 Adjust the previous pointer of the new head to point to the last node.
Deleting from the End:
 Adjust the next pointer of the second-to-last node to point to the head.
 Adjust the previous pointer of the head to point to the second-to-last
node.
Deleting a Specific Node:
 Traverse the list to find the node.
 Adjust the pointers of the previous and next nodes to bypass the node to
be deleted.
3. Traversal
Forward Traversal:
 Start from the head and move forward using the next pointer.
 Continue until you reach the head again.
Backward Traversal:
 Start from the head and move backward using the previous pointer.
 Continue until you reach the head again.
4. Searching
 Traverse the list using either the next or previous pointers.
 Compare each node's data with the target value until the value is found or
the list is fully traversed.
Tree - Terminology
In linear data structure data is organized in sequential order and in non-linear
data structure data is organized in random order.

Page | 19
20 | P a g e

Tree is a very popular non-linear data structure used in wide range of


applications. Tree is a non-linear data structure which organizes data in
hierarchical structure and this is a recursive definition. Tree data structure is a
collection of data (Node) which is organized in hierarchical structure
recursively.
In tree data structure, every
individual element is called
as Node. Node in a tree data
structure stores the actual
data of that particular element
and link to next element in
hierarchical structure.

In a tree data structure, if we


have N number of nodes then
we can have a maximum of N-
1 number of links.

Terminology
In a tree data structure, we use
the following terminology...
1. Root
In a tree data structure, the first
node is called as Root Node.
Every tree must have root node. We can say that root node is the origin of tree
data structure. In any tree, there must be only one root node. We never have
multiple root nodes in a tree.

2. Edge
In a tree data structure, the
connecting link between any
two nodes is called as EDGE.
In a tree with 'N' number of
nodes there will be a
maximum of 'N-1' number of
edges.

3. Parent
In a tree data structure, the
node which is predecessor of
any node is called
as PARENT NODE. In simple
words, the node which has
branch from it to any other
node is called as parent

Page | 20
21 | P a g e

node. Parent node can also be defined as "The node which has child /
children".

4. Child
In a tree data structure, the
node which is descendant of
any node is called as CHILD
Node. In simple words, the
node which has a link from
its parent node is called as
child node. In a tree, any
parent node can have any
number of child nodes. In a
tree, all the nodes except root are child nodes.

5. Siblings
In a tree data structure,
nodes which belong to same
Parent are called
as SIBLINGS. In simple
words, the nodes with same
parent are called as Sibling
nodes.

6. Leaf
In a tree data structure, the
node which does not have a
child is called as LEAF
Node. In simple words, a
leaf is a node with no child.

In a tree data structure, the


leaf nodes are also called
as External Nodes.
External node is also a node with no child. In a tree, leaf node is also called as
'Terminal' node.

7. Internal Nodes
In a tree data structure, the
node which has atleast one
child is called as INTERNAL
Node. In simple words, an
internal node is a node with
atleast one child.

In a tree data structure,


Page | 21
22 | P a g e

nodes other than leaf nodes are called as Internal Nodes. The root node is
also said to be Internal Node if the tree has more than one node. Internal
nodes are also called as 'Non-Terminal' nodes.

8. Degree
In a tree data structure, the
total number of children of a
node is called as DEGREE of
that Node. In simple words,
the Degree of a node is total
number of children it has.
The highest degree of a node
among all the nodes in a tree
is called as 'Degree of Tree'

9. Level
In a tree data structure, the
root node is said to be at
Level 0 and the children of
root node are at Level 1 and
the children of the nodes
which are at Level 1 will be
at Level 2 and so on... In
simple words, in a tree each
step from top to bottom is
called as a Level and the
Level count starts with '0' and
incremented by one at each
level (Step).

10. Height
In a tree data structure, the total number of edges from leaf node to a
particular node in the longest path is called as HEIGHT of that Node. In a tree,
height of the root node is said to be height of the tree. In a tree, height of
all leaf nodes is '0'.

11. Depth
In a tree data structure, the
total number of egdes from
root node to a particular node is
called as DEPTH of that
Node. In a tree, the total
number of edges from root
node to a leaf node in the longest path is said to be Depth of the tree. In

Page | 22
23 | P a g e

simple words, the highest depth of any leaf node in a tree is said to be depth of
that tree. In a tree, depth of the root node is '0'.

12. Path
In a tree data structure, the
sequence of Nodes and Edges
from one node to another
node is called
as PATH between that two
Nodes. Length of a Path is
total number of nodes in that
path. In below example the path A - B - E - J has length 4.

13. Sub Tree


In a tree data structure, each
child from a node forms a
subtree recursively. Every child
node will form a subtree on its
parent node.

Tree Representations
A tree data structure can be represented in two methods. Those methods are
as follows...
1. Linked List Representation
2. Left Child - Right Sibling Representation

1. List Representation
In this representation, we use
two types of nodes one for
representing the node with
data called 'data node' and
another for representing only
references called 'reference
node'. We start with a 'data
node' from root node in the
tree. Then it is linked to an internal node through a 'reference node' which is
further linked to any other node directly. This process repeats for all the nodes
in the tree.
The above example tree can be represented using List representation as
follows...

2. Left Child - Right Sibling Representation


In this
representation, we
use list with one
type of node which
Page | 23
24 | P a g e

consists of three fields namely Data field, Left child reference field and Right
sibling reference field. Data field stores the actual value of a node, left
reference field stores the address of the left child and right reference field
stores the address of the right sibling node. Graphical representation of that
node is as follows...

In this
representation,
every node's
data field stores
the actual value of
that node. If that
node has left
child, then left
reference field
stores the
address of that
left child node
otherwise stores
NULL. If that
node has right sibling, then right reference field stores the address of right
sibling node otherwise stores NULL.
The above example tree can be represented using Left Child - Right Sibling
representation as in the figure...
Binary Tree Data structure
In a normal tree, every node can
have any number of children.
Binary tree is a special type of
tree data structure in which every
node can have a maximum of 2
children. One is known as left
child and the other is known as
right child.
A tree in which every node can
have a maximum of two children is
called as Binary Tree.
In a binary tree, every node can have either 0 children or 1 child or 2 children
but not more than 2
children.
Example

There are different types of


binary trees and they are...
1. Strictly Binary Tree
Page | 24
25 | P a g e

In a binary tree, every node can have a maximum of two children. But in strictly
binary tree, every node should have exactly two children or none. That means
every internal node must have exactly two children. A strictly Binary Tree can
be defined as follows...
A binary tree in which every node has either two or zero number of children is
called Strictly Binary Tree
Strictly binary tree is also called as Full Binary Tree or Proper Binary
Tree or 2-Tree
Strictly binary tree data structure is used to represent mathematical
expressions.
Example

2. Complete Binary Tree


In a binary tree, every node can have a maximum of two children. But in strictly
binary tree, every node should have exactly two children or none and in
complete binary tree all the nodes must have exactly two children and at every
level of complete binary tree there must be 2 level number of nodes. For example
at level 2 there must be 2 2 = 4 nodes and at level 3 there must be 2 3 = 8
nodes.
A binary tree in which
every internal node
has exactly two
children and all leaf
nodes are at same
level is called
Complete Binary Tree.

Complete binary tree is


also called
as Perfect
Binary Tree

3.
Extended
Binary
Tree
A binary
tree can be
converted
Page | 25
26 | P a g e

into Full Binary tree by adding dummy nodes to existing nodes wherever
required.
The full binary tree obtained by adding dummy nodes to a binary tree is called
as Extended Binary Tree.

Binary Tree Representations


A binary tree data structure is represented using two methods. Those methods
are as follows...
1. Array Representation
2. Linked List
Representation
Consider the following binary
tree...
1. Array
Representation of
Binary Tree
In array representation of
binary tree, we use one
dimensional array (1-D Array) to represent a binary tree.
Consider the above example of binary tree and it is represented as follows...

To represent a binary tree of depth 'n' using array representation, we need one
dimensional array with a maximum size of 2n + 1.
2. Linked List Representation of Binary Tree
We use double linked list to represent a binary tree. In a double linked list,
every node consists of three fields. First field for storing left child address,
second for storing actual data and third for storing right child address.
In this linked list representation, a node has the following structure...

The above example of binary tree represented using Linked list representation
is shown as follows...

Page | 26
27 | P a g e

Page | 27
28 | P a g e

Introduction to Graphs
Graph is a non linear data structure. It contains set of points known as nodes
(or vertices) and set of links known as edges (or Arcs). Here edges are used to
connect the vertices. A graph is defined as follows...
Graph is a collection of vertices and arcs in which vertices are connected with
arcs
Graph is a collection of nodes and edges in which nodes are connected with
edges
Generally, a graph G is represented as G = ( V , E ), where V is set of
vertices and E is set of edges.
Example
The following is a graph with 5 vertices and 6 edges.
This graph G can be defined as G = ( V , E )
Where V = {A,B,C,D,E} and E = {(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}.

Graph Terminology
We use the following terms in graph data structure...
Vertex
Individual data element of a graph is called as Vertex. Vertex is also known
as node. In above example graph, A, B, C, D & E are known as vertices.
Edge
An edge is a connecting link between two vertices. Edge is also known as Arc.
An edge is represented as (startingVertex, endingVertex). For example, in
above graph the link between vertices A and B is represented as (A,B). In above
example graph, there are 7 edges (i.e., (A,B), (A,C), (A,D), (B,D), (B,E), (C,D),
(D,E)).

Edges are three types.


1. Undirected Edge - An undirected egde is a bidirectional edge. If there is
undirected edge between vertices A and B then edge (A , B) is equal to
edge (B , A).
2. Directed Edge - A directed egde is a unidirectional edge. If there is
directed edge between vertices A and B then edge (A , B) is not equal to
edge (B , A).
3. Weighted Edge - A weighted egde is a edge with value (cost) on it.
Undirected Graph
A graph with only undirected edges is said to be undirected graph.
Directed Graph
A graph with only directed edges is said to be directed graph.
Mixed Graph

Page | 28
29 | P a g e

A graph with both undirected and directed edges is said to be mixed graph.
End vertices or Endpoints
The two vertices joined by edge are called end vertices (or endpoints) of that
edge.
Origin
If a edge is directed, its first endpoint is said to be the origin of it.
Destination
If a edge is directed, its first endpoint is said to be the origin of it and the other
endpoint is said to be the destination of that edge.
Adjacent
If there is a edge between vertices A and B then both A and B are said to be
adjacent. In other words, vertices A and B are said to be adjacent if there is a
edge between them.
Incident
Edge is said to be incident on a vertex if the vertex is one of the endpoints of
that edge.
Outgoing Edge
A directed edge is said to be outgoing edge on its origin vertex.
Incoming Edge
A directed edge is said to be incoming edge on its destination vertex.
Degree
Total number of edges connected to a vertex is said to be degree of that
vertex.
Indegree
Total number of incoming edges connected to a vertex is said to be indegree of
that vertex.
Outdegree
Total number of outgoing edges connected to a vertex is said to be outdegree
of that vertex.
Parallel edges or Multiple edges
If there are two undirected edges with same end vertices and two directed
edges with same origin and destination, such edges are called parallel edges or
multiple edges.
Self-loop
Edge (undirected or directed) is a self-loop if its two endpoints coincide with
each other.
Simple Graph
A graph is said to be simple if there are no parallel and self-loop edges.
Path
A path is a sequence of alternate vertices and edges that starts at a vertex and
ends at other vertex such that each edge is incident to its predecessor and
successor vertex.
Graph Representations
Graph data structure is represented using following representations...
1. Adjacency Matrix
2. Incidence Matrix
3. Adjacency List
Adjacency Matrix
Page | 29
30 | P a g e

In this representation, graph is represented using a matrix of size total number


of vertices by total number of vertices. That means graph with 4 vertices is
represented using a matrix of size 4X4. In this matrix, both rows and columns
represents vertices. This matrix is filled with either 1 or 0. Here, 1 represents
that there is a edge from row vertex to column vertex and 0 represents that
there is no edge from row vertex to column vertex.

For example, consider the following undirected graph representation...

Directed graph representation...

Incidence Matrix
In this representation, graph is represented using a matrix of size total number
of vertices by total number of edges. That means graph with 4 vertices and 6
edges is represented using a matrix of size 4X6. In this matrix, rows represents
vertices and columns represents edges. This matrix is filled with 0 or 1 or -1.
Here, 0 represents that the row edge is not connected to column vertex, 1
represents that the row edge is connected as outgoing edge to column vertex
and -1 represents that the row edge is connected as incoming edge to column
vertex.

For example, consider the following directed graph representation...

Page | 30
31 | P a g e

Adjacency List
In this representation, every vertex of a graph contains list of its adjacent
vertices.

For example, consider the following directed graph representation implemented


using linked list...
This representation can also be implemented using array as follows..
Graph Traversal -
DFS
Graph traversal is a
technique used for
searching vertex in a
graph. The graph
traversal is also used to
decide the order of
vertices to be visited in
the search process. A
graph traversal finds
the egdes to be used in
the search process
without creating
loops. That means
using graph traversal
we visit all the
vertices of graph
without getting into
looping path.

There are two graph


traversal techniques
and they are as
follows...
1. DFS (Depth
First Search)
2. BFS (Breadth
First Search)
DFS (Depth First
Search)
DFS traversal of a
graph produces
a spanning tree as
final result. Spanning
Tree is a graph
without loops. We
use Stack data
structure with
maximum size of total
number of vertices in
Page | 31
32 | P a g e

the graph to implement DFS traversal.

We use the following steps to implement DFS traversal...


 Step 1 - Define a Stack of size total number of vertices in the graph.
 Step 2 - Select
any vertex
as starting
point for
traversal. Visit
that vertex and
push it on to
the Stack.
 Step 3 - Visit
any one of the
non-
visited adjace
nt vertices of a
vertex which is
at the top of
stack and push
it on to the
stack.
 Step 4
- Repeat step 3
until there is no
new vertex to
be visited from
the vertex
which is at the
top of the
stack.
 Step 5 - When
there is no new
vertex to visit
then use back
tracking and
pop one vertex
from the stack.
 Step 6
- Repeat steps
3, 4 and 5 until
stack becomes
Empty.
 Step 7 - When
stack becomes

Page | 32
33 | P a g e

Empty, then produce final spanning tree by removing unused edges from
the graph
Back tracking is coming back to the vertex from which we reached the
current vertex.

Example

Page | 33
34 | P a g e

Page | 34
35 | P a g e

Graph Traversal - BFS

Graph traversal is a technique used for searching vertex in a graph. The graph
traversal is also used to decide the order of vertices to be visited in the search
process. A graph traversal finds the egdes to be used in the search process
without creating loops. That means using graph traversal we visit all the
vertices of graph without getting into looping path.

There are two graph traversal techniques and they are as follows...

1. DFS (Depth First Search)


2. BFS (Breadth First Search)

BFS (Breadth First Search)

BFS traversal of a graph produces a spanning tree as final result. Spanning


Tree is a graph without loops. We use Queue data structure with maximum
size of total number of vertices in the graph to implement BFS traversal.

We use the following steps to implement BFS traversal...

 Step 1 - Define a Queue of size total number of vertices in the graph.


 Step 2 - Select any vertex as starting point for traversal. Visit that
vertex and insert it into the Queue.
 Step 3 - Visit all the non-visited adjacent vertices of the vertex which is
at front of the Queue and insert them into the Queue.
 Step 4 - When there is no new vertex to be visited from the vertex which
is at front of the Queue then delete that vertex.
 Step 5 - Repeat steps 3 and 4 until queue becomes empty.
 Step 6 - When queue becomes empty, then produce final spanning tree
by removing unused edges from the graph

Page | 35
36 | P a g e

Example

Page | 36
37 | P a g e

Page | 37
38 | P a g e

What is Graph?
 Graph is an abstract data type.
 It is a pictorial representation of a set of objects where some pairs of
objects are connected by links.
 Graph is used to implement the undirected graph and directed graph
concepts from mathematics.
 It represents much real life application. Graphs are used to represent
the networks. Network includes path in a city, telephone network etc.
 It is used in social networks like Facebook, LinkedIn etc.
Graph consists of two following components:
1. Vertices
2. Edges
 Graph is a set of vertices (V) and set of edges (E).
 V is a finite number of vertices also called as nodes.
 E is a set of ordered pair of vertices representing edges.
 For Example On facebook, everything is a node. That includes User,
Photo, Album, Event, Group, Page, Comment, Story, Video, Link,
Note...anything that has data is a node.
 Every relationship is an edge from one node to another. Whether you
post a photo, join a group, like a page etc., a new edge is created for
that relationship.

The above figures represent the graphs. The set representation for each of
these graphs are as follows:
Graph 1:
V = {A, B, C, D, E, F}
E = {(A, B), (A, C), (B, C), (B, D), (D, E), (D, F), (E, F)}

Graph 2:
V = {A, B, C, D, E, F}
E = {(A, B), (A, C), (B, D), (C, E), (C, F)}

Graph 3:
V = {A, B, C}
E = {(A, B), (A, C), (C, B)}
Directed Graph
 If a graph contains ordered pair of vertices, is said to be a Directed
Graph.

Page | 38
39 | P a g e

 If an edge is represented using a pair of vertices (V 1, V2), the edge is


said to be directed from V1 to V2.
 The first element of the pair V1 is called the start vertex and the second
element of the pair V2 is called the end vertex.

Set of Vertices V = {1, 2, 3, 4, 5, 5}


Set of Edges W = {(1, 3), (1, 5), (2, 1), (2, 3), (2, 4), (3, 4), (4, 5)}
Undirected Graph
 If a graph contains unordered pair of vertices, is said to be an
Undirected Graph.
 In this graph, pair of vertices represents the same edge.

Set of Vertices V = {1, 2, 3, 4, 5}


Set of Edges E = {(1, 2), (1, 3), (1, 5), (2, 1), (2, 3), (2, 4), (3, 4), (4, 5)}
 In an undirected graph, the nodes are connected by undirected arcs.
 It is an edge that has no arrow. Both the ends of an undirected arc are
equivalent, there is no head or tail.
Representation of Graphs
Adjacency Matrix
 Adjacency matrix is a way to represent a graph.
 It shows which nodes are adjacent to one another.
 Graph is represented using a square matrix.
Graph can be divided into two categories:
a. Sparse Graph
b. Dense Graph
Sparse graph contains less number of edges.
Dense graph contains more number of edges as compared to sparse
graph.
 Adjacency matrix is best for dense graph, but for sparse graph, it is not
required.
 Adjacency matrix is good solution for dense graph which implies having
constant number of vertices.
Adjacency matrix of an undirected graph is always a symmetric matrix
which means an edge (i, j) implies the edge (j, i).

Page | 39
40 | P a g e

The above graph represents undirected


graph with the adjacency matrix
representation. It shows adjacency matrix of
undirected graph is symmetric. If there is an
edge (2, 4), there is also an edge (4, 2).

 Adjacency matrix of a directed graph is never symmetric adj[i][j] = 1,


indicated a directed edge from vertex i to vertex j.

 The above graph represents directed graph with the adjacency matrix
representation. It shows adjacency matrix of directed graph which is
never symmetric. If there is an edge (2, 4), there is not an edge (4, 2). It
indicates direct edge from vertex i to vertex j.
Advantages of Adjacency Matrix
 Adjacency matrix representation of graph is very simple to implement.
 Adding or removing time of an edge can be done in O(1) time. Same
time is required to check, if there is an edge between two vertices.
 It is very convenient and simple to program.
Disadvantages of Adjacency Matrix
 It consumes huge amount of memory for storing big graphs.
 It requires huge efforts for adding or removing a vertex. If you are
constructing a graph in dynamic structure, adjacency matrix is quite
slow for big graphs.
Adjacency List
 Adjacency list is another representation of graphs.
 It is a collection of unordered list, used to represent a finite graphs.

Page | 40
41 | P a g e

 Each list describes the set of neighbors of a vertex in the graph.


 Adjacency list requires less amount of memory.
 For every vertex, adjacency list stores a list of vertices, which are
adjacent to the current one.
 In adjacency list, an array of linked list is used. Size of the array is equal
to the number of vertices.

 In adjacency list, an entry array[i] represents the linked list of vertices


adjacent to the ith vertex.
 Adjacency list allows to store the graph in more compact form than
adjacency matrix.
 It allows to get the list of adjacent vertices in O(1) time.
Disadvantages of Adjacency List
 It is not easy for adding or removing an edge to/from adjacent list.
 It does not allow to make an efficient implementation, if dynamically
change of vertices number is required.
Important Note:
Vertex: Each node of the graph is represented as a vertex.
Edge: It represents a path between two vertices or a line between two
vertices.
Path: It represents a sequence of edges between the two vertices.
Adjacency: If two nodes or vertices are connected to each other through
an edge, it is said to be an adjacency.
Graph Traversal
 Graph traversal is a process of checking or updating each vertex in a
graph.
 It is also known as Graph Search.
 Graph traversal means visiting each and exactly one node.
 Tree traversal is a special case of graph traversal.
There are two techniques used in graph traversal:
1. Depth First Search
2. Breadth First Search
Depth First Search
 Depth first search (DFS) is used for traversing a finite graph.
 DFS traverses the depth of any particular path before exploring its
breadth.
 It explores one subtree before returning to the current node and then
exploring the other subtree.
 DFS uses stack instead of queue.
Page | 41
42 | P a g e

 It traverses a graph in a depth-ward motion and gets the next vertex to


start a search when a dead end occurs in any iteration.
Depth First Search (DFS)
The aim of DFS algorithm is to traverse the
graph in such a way that it tries to go far from
the root node. Stack is used in the
implementation of the depth first search. Let’s
see how depth first search works with respect
to the following graph:

As stated before, in DFS, nodes are visited by going through the depth of
the tree from the starting node. If we do the depth first traversal of the
above graph and print the visited node, it will be “A B E F C D”. DFS visits
the root node and then its children nodes until it reaches the end node, i.e.
E and F nodes, then moves up to the parent nodes.
Algorithmic Steps
Step 1: Push the root node in the Stack.
Step 2: Loop until stack is empty.
Step 3: Peek the node of the stack.
Step 4: If the node has unvisited child nodes, get the unvisited child node, mark it as
traversed and push it on stack.
Step 5: If the node does not have any unvisited child nodes, pop the node from the stack.

 As you see both the figures, DFS


does not go though all the edges.
The tree contains all the vertices of
the graph if it is connected to the nodes and is called as Graph

Page | 42
43 | P a g e

Spanning Tree. Graph spanning tree is exactly corresponds to the


recursive calls of DFS.
 If a graph is disconnected then DFS will not be able to visit all of its
vertices.
 DFS will pop up all the vertices from the stack which do not have
adjacent nodes. The process is going on until we find a node that has
unvisited adjacent node and if there is no more adjacent node, DFS is
over.
DFS example
Let's see how the Depth First Search algorithm works with an example. We
use an undirected graph with 5 vertices.

We start from vertex 0, the DFS algorithm starts by putting it in the Visited
list and putting all its adjacent vertices in the stack.

Next, we visit the element at the top of stack i.e. 1 and go to its adjacent
nodes. Since 0 has already been visited, we visit 2 instead.

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of


the stack and visit it.

Page | 43
44 | P a g e

After we visit the last element 3, it doesn't have any unvisited adjacent
nodes, so we have completed the Depth First Traversal of the graph.

Breadth First Search (BFS)


This is a very different approach for traversing the graph nodes. The aim of
BFS algorithm is to traverse the graph as close as possible to the root
node. Queue is used in the implementation of the breadth first search.
Let’s see how BFS traversal works with
respect to the following graph:

If we do the breadth first traversal of the


above graph and print the visited node
as the output, it will print the following
output. “A B C D E F”. The BFS visits the
nodes level by level, so it will start with
level 0 which is the root node, and then
it moves to the next levels which are B,
C and D, then the last levels which are E and F.
Algorithmic Steps
Step 1: Push the root node in the Queue.
Step 2: Loop until the queue is empty.
Step 3: Remove the node from the Queue.
Step 4: If the removed node has unvisited child nodes, mark them as visited and insert the
unvisited children in the queue.
2. Breadth First Search
 Breadth first search is used for traversing a finite graph.
 It visits the neighbor vertices before visiting the child vertices.
 BFS uses a queue for search process and gets the next vertex to start a
search when a dead end occurs in any iteration.
 It traverses a graph in a breadth-ward motion.
 It is used to find the shortest path from one vertex to another.
Page | 44
45 | P a g e

 The main purpose of BFS is to traverse the graph as close as possible to


the root node.
 BFS is a different approach for traversing the graph nodes.
BFS example
Let's see how the Breadth First Search algorithm works with an example.
We use an undirected graph with 5 vertices.

We start from vertex 0, the BFS algorithm starts by putting it in the Visited
list and putting all its adjacent vertices in the stack.

Next, we visit the element at the front of queue i.e. 1 and go to its adjacent
nodes. Since 0 has already been visited, we visit 2 instead.

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the back


of the queue and visit 3, which is at the front of the queue.

Page | 45
46 | P a g e

Only 4 remains in the queue since the only adjacent node of 3 i.e. 0 is
already visited. We visit it.

Since the queue is empty, we have completed the Depth First Traversal of
the graph.
Spanning Tree and Minimum Spanning Tree
Spanning tree
A spanning tree is a sub-graph of an undirected and a connected graph,
which includes all the vertices of the graph having a minimum possible
number of edges. If a vertex is missed, then it is not a spanning tree.
The edges may or may not have weights assigned to them.
The total number of spanning trees with n vertices that can be created
from a complete graph is equal to n(n-2).
Example of a Spanning Tree
Let the original graph be:

Some of the possible spanning trees that can be created from the above
graph are:

Page | 46
47 | P a g e

We have n = 4, thus the maximum number of possible spanning trees is


equal to 44-2 = 16. Thus, 16 spanning trees can be formed from the above
graph.
Minimum Spanning Tree
A minimum spanning tree is a spanning tree in which the sum of the
weight of the edges is as minimum as possible.
Example of a Spanning Tree
Let's understand the above definition with the help of the example below.
The initial graph is:

The possible spanning trees from the above graph are:

The minimum spanning tree from the above spanning trees is:

Page | 47
48 | P a g e

The minimum spanning tree from a graph is found using the following
algorithms:
Prim's Algorithm
Kruskal's Algorithm
Prim's Algorithm
Prim's algorithm is a minimum spanning tree algorithm that takes a graph
as input and finds the subset of the edges of that graph which
form a tree that includes every vertex
has the minimum sum of weights among all the trees that can be formed
from the graph
How Prim's algorithm works
It falls under a class of algorithms called greedy algorithms which find the
local optimum in the hopes of finding a global optimum.
We start from one vertex and keep adding edges with the lowest weight
until we we reach our goal.
The steps for implementing Prim's algorithm are as follows:
 Initialize the minimum spanning tree with a vertex chosen at random.
 Find all the edges that connect the tree to new vertices, find the
minimum and add it to the tree
 Keep repeating step 2 until we get a minimum spanning tree
 Example of Prim's algorithm

Page | 48
49 | P a g e

Kruskal's Algorithm
Kruskal's algorithm is a minimum spanning tree algorithm that takes a graph as
input and finds the subset of the edges of that graph which
form a tree that includes every vertex
Page | 49
50 | P a g e

has the minimum sum of weights among all the trees that can be formed
from the graph
How Kruskal's algorithm works
It falls under a class of algorithms called greedy algorithms which find the local
optimum in the hopes of finding a global optimum.
We start from the edges with the lowest weight and keep adding edges
until we we reach our goal.
The steps for implementing Kruskal's algorithm are as follows:
Sort all the edges from low weight to high
Take the edge with the lowest weight and add it to the spanning tree. If
adding the edge created a cycle, then reject this edge.
Keep adding edges until we reach all vertices.
Example of Kruskal's algorithm

Page | 50
51 | P a g e

Page | 51

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy