Linked Lists: Operations and Applications
Linked Lists: Operations and Applications
L T P C
Code
DATA STRUCTURES LAB
100223218
0 1 2 2
0
UNIT II
Linked Lists: Singly linked lists: representation and operations, doubly linked lists and circular linked lists,
Comparing arrays and linked lists, Applications of linked lists.
Sample Experiments:
1. Write a program to implement the following operations.
a. Insert b. Deletion c. Traversal
2. Write a program to store name, roll no, and marks of students in a class using circular double
linked list.
3. Write a program to perform addition of given two polynomial expressions using linked list.
Linked list:
Linked list is a linear data structure that contains sequence of elements such that each element
links to its next element in the sequence. Each element in a linked list is called as "Node".
➢ Linked List is a very commonly used linear data structure which consists of set of nodes in
a sequence.
➢ Linked list is a collection of nodes which are not necessary to stored in adjacent
memory locations.
➢ Each node has two fields known as data and link. Data field stores actual data and link
contains address of next node to point to the next node.
➢ Linked Lists are used to create trees and graphs.
➢ A linked list is a collection of nodes ordered by links that are stored as part of node. They
are not ordered by their physical placement in memory.
➢ Chain is a single linked list that comprised of zero or more nodes and with 0 in last node.
when the number of nodes is zero, chain is empty. the last node of chain has 0 link.
Problems with Arrays:
1. Prediction of size – Size of an array must be specified precisely at the beginning which
may be difficult task in many practical applications.
2. Static memory allocation—Memory allotment is required at the compile time.
3. Wastage of space—inefficient usage of storage memory.
4. Inefficient implementation of insertions and deletions as they require shift operations.
Advantages of Linked Lists
● They are a dynamic in nature which allocates the memory when required.
● Insertion and deletion operations can be easily implemented.
● Size of linked list can grow or shrink in size during the execution of a program.
● In Linked Lists we don't need to know the size in advance
● Stacks and queues can be easily executed.
● Linked List provides flexibility in allowing the items to be rearranged efficiently.
Disadvantages of Linked Lists
● The memory is wasted as pointers require extra memory for storage.
● Access time is linear O(n). No element can be accessed randomly; it has to access each
node sequentially.
● Many basic operations—such as obtaining the last node of the list, finding a node that
contains a given datum, or locating the place where a new node should be inserted—may
require iterating through most or all of the list element
● Reverse Traversing is difficult in linked list.
Diagrammatic(graphical) representation:
Example:
Struct node
{
int data;
Struct node *next;
} *new, *head, *temp, *d;
➢ Create a list
➢ Display the contents of list
➢ Inserting node into the list
➢ Deleting node from the list
Create a list:
Creating a singly linked list starts with creating a node. Sufficient memory has
to be allocated for creating a node. The information is stored in the memory,
allocated by using the malloc () function. After allocating memory for the
structure of type node, the information for the item (i.e., data) has to be read
from the user, set next field to NULL and finally returns the address of the node
New node
10 NULL
NULL
Algorithm:
1. Create a new Node which has two attributes: data and next. Next is a
pointer to the next node.
New->data=x;
New->next=NULL;
2. It first checks, whether the head is equal to null which means the list is
empty.
a. If the list is empty, both head and tail will point to the newly added
node.
Head=new;
Temp=new;
b. If the list is not empty, the new node will be added to end of the list
such that tail's next will point to the newly added node. This new
node will become the new tail of the list.
Temp->next=new;
Temp=new;
[Link]
Display the contents of list:
Display operation will display the nodes present in the list
Algorithm:
1. Define a node temp which initially points to the head of the list.
Temp=head
[Link] each node by makin temp to point to node next to it in each iteration.
Temp=temp->next
[Link]
Display ( )function:
void display()
{
temp=head;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
Insertion of a Node:
One of the most primitive operations that can be done in a singly linked list is
the
Insertion of a node. Memory is to be allocated for the new node (in a similar
way that is done while creating a list) before reading the data. The new node
will contain empty data field and empty next field. The data field of the new
node is then stored with the information read from the user. The next field of the
new node is assigned to NULL. The new node can then be inserted at three
different places namely:
• Inserting a node at the beginning.
• Inserting a node at the end.
• Inserting a node at specified position.
Example:
1. Create a new node, say newNode points to the newly created node.
NULL
2. Link the newly created node with the head node, i.e. the newnode will now
points to the head node
3. Make the new node as the head node, i.e. now head node will points to the
head
Algorithm:
1. Create a new node i.e new
new=(struct node*)malloc(sizeof(struct node)
2. Read value into data
part of new node i.e
‘x’. new->data=x
new->next=NULL
3. Insert new node to the start node of list
New->next=head
4. Now, new node becomes the head
New=head
5. stop
Null
2. Traverse to the last node of the linked list and connect the last nodeof the list
with the new node, i.e. last node will now point to new node.
(temp->next = new).
Algorithm:
6. While(temp->next!=NULL)
Begin
Temp=temp->next
End
7. Now ‘temp’ will point the last node of single linked list.
8. Temp->next=new
9. Stop
steps to Inserting a node at specified position.:
1. Create a new node.
2. Traverse to the n-1th position of the linked list and connect the new node with
the n+1th node. Means the new node should also point to the same node that the
n-1th node is pointing to (new->next = temp>next where temp is the n-1th
node).
3. Now at last connect the n-1th node with the new node i.e. the n-1th node will
now point to new node. (temp->next = newwhere tempis the n-1th node).
4.
Algorithm:
1. Create a new node i.e new
new=(struct node*)malloc(sizeof(struct node)
2. Read value into data
part of new node i.e
‘x’.
new->data=x
new->next=NULL
3. Read the position i.e ‘pos’
4. Store start value in temporary pointer i.e ‘temp’
5. temp=head
6. Move ‘temp’ value till pos-1
7. for (i=0;i<pos-1;i++)
begin
temp=temp->next
end
8. Now assign ‘temp->next’ to the next pointer of ‘new’
new- >next=temp->next
9. Now link the node
temp->next=new
10. stop
Deletion of a node:
Another primitive operation that can be done in a singly linked list is the
deletion of a node. Memory is to be released for the node to be deleted. A node
can be deleted from the list from three different places namely.
• Deleting a node at the beginning.
• Deleting a node at the end.
• Deleting a node at specified position.
Steps to Deleting a node at the beginning:
1. Copy the address of first node i.e., headnode to some temp variable say to Delete.
Algorithm:
1. Start
2. If we delete the beginning node then second node will become the head node.
For that store head address in temporary pointer i.e., ‘temp’ after move head
pointer to second node and delete the first node i.e. ‘temp’
Temp=head
3. Move the head to the second node of the linked list
Head=head->next
4. free(temp);
5. stop
Steps to Deleting a node at the end.:
1. Traverse to the last node of the linked list keeping track of the second last
node in some temp variable say secondLastNode (TEMP).
2. If the last node is the head node then make the head node as NULL else
disconnect the second last node with the last node i.e. temp->next =
NULL.
3. Free the memory occupied by the last node.
Null
Algorithm:
1. start
Algorithm:
1. start
2. Read the position where to delete the node i.e ‘pos
3. Store head value in temporary pointer i.e ‘temp
Team=head’
4. Move ‘temp’ pointer till position-1
5. for(i=1;i<pos-1;i++)
Begin
temp=temp->next
end
6. Now give name to temps’s next node i.e ‘d’
d=temp->next
7. temp->next=d->next
8.d->next=NULL
[Link](d)
[Link]
Complete single linked list(SLL)programme:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*new,*head,*temp,*d;
void create();
void insbeg();
void inspos();
void insend();
void delbeg();
void delpos();
void delend();
void display();
void main()
{
int ch; clrscr();
printf("[Link]..[Link]..[Link]..[Link]..[Link]..[Link]..[Link]
lay..[Link]..\n");
while(1)
{
printf("enter your choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1:create();break;
case 2:insbeg();break;
case 3:inspos();break;
case 4:insend();break;
case 5:delbeg();break;
case 6:delpos();break;
case 7:delend();break;
case 8:display();break;
case 9:exit(1);break;
default:printf("wrong choics entered\n");
}}}
void create()
{
int x,n,i;
printf("enter no elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
new=(struct node*)malloc(sizeof(struct node));
printf("enter the data");
scanf("%d",&x);
new->data=x;
new->next=NULL;
if(head==NULL)
{
head=new;
temp=new;
}
else
{
temp->next=new;
temp=new;
}}}
void insbeg()
{
int x;
new=(struct node*)malloc(sizeof(struct node));
printf("enter data into node:");
scanf("%d",&x);
new->data=x;
new->next=head;
head=new;
}
void insend()
{
int x;
temp=head;
new=(struct node*)malloc(sizeof(struct node));
printf("enter data into last:");
scanf("%d",&x);
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=new;
new->data=x;
new->next=NULL;
temp=new;
}
void inspos()
{
int i,pos,x;
printf("enter position to insert:");
scanf("%d",&pos);
printf("enter data to insert in %d position",pos);
scanf("%d",&x);
new=(struct node*)malloc(sizeof(struct node));
temp=head;
for(i=1;i<pos-1;i++)
{
temp=temp->next;
}
new->data=x;
new->next=temp->next;
temp->next=new;
}
void display()
{
temp=head;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
printf("NULL\n");
}
void delbeg()
{
temp=head;
printf("deleted node is %d",temp->data);
head=head->next;
temp->next=NULL;
free(temp);
}
void delpos()
{
int pos,i;
printf("enter position to delete:");
scanf("%d",&pos);
temp=head;
for(i=0;i<pos-1;i++)
{
temp=temp->next;
}
d=temp->next;
printf("deleted node is %d",d->data);
temp->next=d->next;
d- >next=NULL;
free(d);
}
void delend()
{
temp=head;
while(temp->next->next!=NULL)
{
temp=temp->next;
}
d=temp->next;
printf("the deleted node is %d",d->data);
temp->next=NULL;
free(temp);
}
Doubly 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 another node only in one direction and we cannot traverse
back. We can solve this kind of problem by using double linked list. Double linked list
can be defined as follows...
Doubly linked list is a collection of nodes linked together in a sequential way.
Each node of the list contains two parts data part and the reference or address
part.
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...
Diagrammatic representation:
Doubly linked list is almost similar to singly linked list except it containstwo
address or reference fields, where one of the address fields contains reference
of the next node and other contains reference of the previousnode.
➢ First node previous and last node next fields of a linked list contains
a NULL value, that determines the start and end of the list.
➢ Doubly linked list is sometimes also referred as bi-directional linked
list since it allows traversal of nodes in both direction.
Doubly linked list is one of the important data structures. Here are various
advantages of doubly linked list.
➢ It uses extra memory when compared to array and singly linked list.
➢ Since elements in memory are stored randomly, hence elements are
accessed sequentially no direct access is allowed.
The basic structure of a node in a doubly linked list contains a data field
and two address fields.
struct node {
int data; // Data field
struct node * prev; // Address of previous node
struct node * next; // Address of next node
}*new,*head,*temp,*d;
Operations on double linked lists:
➢ Create a list
➢ Display the contents of list
➢ Inserting node into the list
➢ Deleting node from the list
Create a list:
Creating a double linked list starts with creating a node. Sufficient memory has
to be allocated for creating a node. The information is stored in the memory,
allocated by using the malloc () function. The function create (), is used for
creating a node, after allocating memory for the structure of type node, the
information for the item (i.e., data) has to be read from the user and set left field
to NULL and right field also set to NULL
1. Create a head node and assign some data to its data field. Make sure
thatthe previous and next address field of the head node must point to
NULL.
2. If list is not empty create nodes and store it’s address in its previous and next
fields.
ALGORITHM:
1. Create a new Node which has three attributes: data, previous and next. Next
is a pointer to the next node and previous is a pointer to the previous node
New->prev=NULL;
New->data=x;
New->next=NULL;
2. It first checks, whether the head is equal to null which means the list is
empty.
a. If the list is empty, both head and tail will point to the newly added node
Head=new;
Temp=new;
b. If the list is not empty, the new node will be added to end of the list such that
tail's next will point to the newly added node and newly added node previous
points to tail. This new node will become the new tail of the list.
Temp->next=new;
New->prev=temp;
Temp=new;
[Link]
Display the contents of list:
Display the contents of list:
Display operation will display the nodes present in the list
Algorithm:
1. Define a node temp which initially points to the head of the list.
Temp=head
[Link] each node by makin temp to point to node next to it in each iteration.
Temp=temp->next
[Link]
Insertion of a Node:
One of the most primitive operations that can be done in a double linked list is
the
Insertion of a node. Memory is to be allocated for the new node (in a similar
way that is done while creating a list) before reading the data. The new node
will contain empty data field, empty previous field and empty next field. The
data field of the new node is then stored with the information read from the
user. The previous and next field of the new node is assigned to NULL. The
new node can then be inserted at three different places namely:
• Inserting a node at the beginning.
• Inserting a node at the end.
• Inserting a node at specified position.
Inserting a node at the beginning:
Example:
1. Create a new node, say new Node points to the newly created node
2. Link the newly created node with the head node, i.e. the new node will now
points to the head node
nul
2. Traverse to the last node of the linked list and connect the last node of the list
with the new node, i.e. last node will now point to new node.
(temp->next = new and new->prev=temp).
null
Algorithm:
1. Create a new node i.e new
new=(struct node*)malloc(sizeof(struct node);
7. Now ‘temp’ will point the last node and last node previou field points
to temp node of double linked list.
Temp->next=new
New->prev=temp
8. Stop
steps to Inserting a node at specified position.:
1. Create a new node.
null
2. Traverse to the n-1th position of the linked list and connect the new node with
the n+1th node. Means the new node should also point to the same node that the n-
1th node is pointing to. (new->next = temp->next where temp is the n-1th node and
temp->next->prev=new).
nul
[Link] at last connect the n-1th node with the new node i.e. the n-1th node will now
point to new node. (temp->next = new and new->prev=tempwhere temp is the n-
1th node)
null
4. final list
null
Algorithm:
1. Create a new node i.e new
new=(struct node*)malloc(sizeof(struct node)
[Link] value into data
part of new node i.e ‘x’.
New->prev=NULL
new->data=x
new->next=NULL
3. Read the position i.e ‘pos’
[Link] start value in temporary pointer i.e ‘temp’
temp=head
[Link] ‘temp’ value till pos-1
for (i=0;i<pos-1;i++)
begin
temp=temp->next
end
[Link] assign ‘temp->next’ to the next pointer of ‘new’ and
temp->next->prev to new node
new- >next=temp->next
temp->next->prev=new
7. Now link the node
temp->next=new
new->prev=temp
[Link]
Deletion of a node:
Another primitive operation that can be done in a double linked list is the
deletion of a node. Memory is to be released for the node to be deleted. A node
can be deleted from the list from three different places namely.
• Deleting a node at the beginning.
• Deleting a node at the end.
• Deleting a node at specified position.
Steps to Deleting a node at the beginning:
1. Copy the address of first node i.e. head node to some temp variable say to Delete.
null
2. Move the head to the second node of the linked list i.e. head = head->next.
null
null
Node to delete
null
2. If the last node is the head node then make the head node as NULL else
disconnect the second last node with the last node i.e. temp->next = NULL
d->prev=NULL
null
null
Algorithm:
1. start
null
5. Reconnect the n-1th node with the n+1th node i.e. temp->next =d->next (Where temp is n-
1th node and d node is the nth node and d->next is the n+1th node). And set d->next->prev=temp
null
6. Free the memory occupied by the nth node i.e. d node.
null
Algorithm:
1. start
7. temp->next=d->next
d->next->prev=temp
8.d->next=NULL
[Link](d)
[Link]
Example:
Creating structure for a node or declaration of node:
Struct node
{
int data;
Struct node *next;
}*new,*head,*temp,*d;
Advantages of a Circular linked list:
• Entire list can be traversed from any node.
• Circular lists are the required data structure when we want a list to be accessed
in a circle or loop.
• Despite of being singly circular linked list we can easily traverse to its previous
node, which is not possible in singly linked list.
Disadvantages of Circular linked list:
• Circular list are complex as compared to singly linked lists.
• Like singly and doubly lists circular linked lists also doesn’t supports direct
accessing of elements.
2.
Algorithm:
1. Create a new Node which has two attributes: data and next. Next is apointer to the
next node.
New->data=x;
New->next=new;
2. It first checks, whether the head is equal to null which means the list is
empty.
a. If the list is empty, both head and tail will point to the newly addednode
Head=new;Temp=new;
b. If the list is not empty, the new node will be added to end of the listsuch that tail's
next will point to the newly added node. This new node will become the new tail of the
list.
Temp->next=new;Temp=new;
New->next=head;
3. stop
Display the contents of list:
Display operation will display the nodes present in the list
Algorithm:
1. Define a node temp which initially points to the head of the list.
Temp=head
Temp=temp->next
6. Stop
Insertion of a Node:
One of the most primitive operations that can be done in a circular linked list is
the
Insertion of a node. Memory is to be allocated for the new node (in a similar
way that is done while creating a list) before reading the data. The new node
will contain empty data field and empty next field. The data field of the new
node is then stored with the information read from the user.
The next field of the new node is assigned to new itself. The new node can then
be inserted at three different places namely:
• Inserting a node at the beginning.
• Inserting a node at the end.
• Inserting a node at specified position.
Steps to Inserting a node at the beginning:
Example:
1. Create a new node, say newNode points to the newly created node.
2. Link the newly created node with the head node, i.e., the new node will
nowpoints to the head node
3. Make the new node as the head node, i.e., now head node will points to
thehead
Algorithm:
1. Create a new node i.e new
2. Traverse to the last node of the linked list and connect the last node of
the list with the new node, i.e. last node will now point to new node.
(temp->next = head).
4. Final list
Algorithm:
8. new->next=head;
[Link]
2. Traverse to the n-1th position of the linked list and connect the new node with
the n+1th node. Means the new node should also point to the same node that
the n-1th node is pointing to. (new->next = temp->next where temp is the n-
1th node).
3. Now at last connect the n-1th node with the new node i.e. the n-1th node will
now point to new node. (temp->next = newwhere temp is the n-1th node).
4. final list
Algorithm:
1. Create a new node i.e new
new=(struct node*)malloc(sizeof(struct node)
[Link] value into data
part of new node i.e ‘x’.
new->data=x
new->next=new
3. Read the position i.e ‘pos’
[Link] start value in temporary pointer i.e ‘temp’
[Link]=head
6. Move ‘temp’ value till pos-1
7. for (i=0;i<pos-1;i++)
begin
temp=temp->next
end
8. Now assign ‘temp->next’ to the next pointer of ‘new’
new- >next=temp->next
9. Now link the node
temp->next=new
10. stop
Deletion of a node:
Another primitive operation that can be done in a singly linked list is the
deletion of a node. Memory is to be released for the node to be deleted. A node
can be deleted from the list from three different places namely.
• Deleting a node at the beginning.
• Deleting a node at the end.
• Deleting a node at specified position.
Steps to Deleting a node at the beginning:
1. Copy the address of first node i.e. head node to some temp variable say to Delete.
2. Move the head to the second node of the linked list i.e. head = head->next.
1. Start
2. If we delete the beginning node then second node will become the head node.
For that store head address in temporary pointer i.e ‘temp’ after move head
pointer to second node and delete the first node i.e ‘temp’
Temp=head
3. while(temp->next! =head)
Begin
Temp=temp->next;
end
4. head=head->next
temp->next=head
free(temp);
5. stop
Steps to Deleting a node at the end.:
1. Traverse to the last node of the linked list keeping track of the second last
node in some temp variable say secondLastNode (TEMP).
2. If the last node is the head node, then make the head node as NULL
elsedisconnect the second last node with the last node i.e. temp->next =
head
9. Reconnect the n-1th node with the n+1th node i.e. temp->next =d-
>next (Where temp is n-1th node and d node is the nth node and d->next is
the n+1th node).
10. Free the memory occupied by the nth node i.e. d node.
Algorithm:
1. start
Polynomials:
Definition: A Polynomial is an expression that contains more than two terms. A
term is made up of coefficient and exponent. For example, of polynomial
equation is P(x)=4x3+6x2+9x+7. In this example 4,6,9,7 are the coefficients
and 3,2,1,0 are the exponents.
Polynomial as an Abstract Data Type:
Abstract Data Type Polynomial
{
Instance: The resultant data is stored in the form of equation i.e. Exponent and
coefficient.
Operations:
Addition (poly1, poly2): It performs addition of two given polynomials
poly1,poly2 and result will be stored in another polynomial.
Subtraction (poly1, poly2): It performs subtraction of two given polynomials
poly1,poly2 and result will be stored in another polynomial.
Multiply (poly1, poly2): It performs multiplication of two given polynomials
poly1,poly2 and result will be stored in another polynomial.
Divide (poly1, poly2): It performs division of two given polynomials
poly1,poly2 and result will be stored in another polynomial.
}
polynomial representation:
Polynomial equation can represent in two ways:
1. Array Representation
2. Linked Representation
Polynomial Representation using an Array: (Method-1)
Polynomial equation can be stored in an array. But here the question is
how to store in an array. An array representation assumes that the
exponents of the given expression are arranged from 0 to the highest
degree, which is represented by the subscript of an array beginning with
4. The coefficients of any exponent are stored inside the array at a
particular index. i.e., The coefficient of exponent 2 is stored in 2 nd index it
an array.
For example, 1: P(x)=4x3+6x2+9x+7
An array representation of the above polynomial is
0 1 2 3 Exponents taken as index
7 9 6 4 Coefficients of
particular
exponents
own indexes
C: coffecient, e: exponent
Operations On polynomials:
➢ Creation and display
➢ Evaluation of polynomial
➢ Addition
Creation and display of polynomial:
Algorithm:
Algorithm:
1) create the structure of polynomial with structure variable p[10]
2) read n as the no of terms in p.
3) read i,sum and Set i=0,sum=0
4) Repeat step 5 while i<n
5) sum=sum+p[i].coeff*pow(x,p[i].expo)
4) Return sum;
5) Exit
Program:
#include<stdio.h>
#include<math.h>
struct poly
{
int coef;
int exp;
};
void main()
{
int x,n,s=0,i;struct poly p[10];
printf(“enter no of elememts :”);
scanf(“%d”,&n);
printf(“enter coefficient & exponent values:”);
for(i=0;i<n;i++)
{
scanf(“%d%d”,&p[i].coef,&p[i].exp);
}
printf(“enter value of x”);
scanf(“%d”,&x);
for(i=0;i<n;i++)
{
s=s+p[i].coef*(pow(x,p[i].exp));
}
printf(“evaluation of expression is %d”,s);
}
Polynomial Addition:
Polynomial addition is nothing but adding a given two or more polynomials
means adding coefficients of two polynomials of equal powers or exponents and
whenever there is no equal powers then simply different power terms are
combined with the resultant polynomial.
Example:
P1=x^3+4x^2+6x and p2=5x^2+7x+9
P1= p2=
Structure of polynomial:
struct node
{
int coef;
int expo;
struct node * next;
} *new, *head, *temp;
Algorithm:Creation of polynomial list for n terms
1. Create head node.
2. Read the number of terms in an expression (read n)
3. Repeat the following steps for n terms.
4. Create new node and add new node to list.
new= (struct node)* malloc(size of(struct node)));
new->coef=co;
new->expo=pow;
new->next=temp->next;
temp->next=new;
temp=new;
Addition of two polynomial lists
Example:
1st polynomial = 5x3 + 4x2 + 2x0
2nd polynomial = 5x^1 - 5x^0
Algorithm: Addition of polynomials:
SPARSE MATRICES REPRESENTATION USING MULTIDIMENSIONAL
ARRAYS:
Definition: In computer programming a matrix can be defined with a 2- dimensional array.
Any array with m columns and n rows represents a m×n matrix. There may be a situation in
which a matrix contains more number of ZERO values than NON-ZERO values. Such matrix
is known as Sparse Matrix. Sparse Matrix is matrix which contains very few non-zero
elements.
➢ A matrix is a two-dimensional data object made of m rows and n columns,therefore
having total m x n values. If most of the elements ofthe matrix have 0 value, then it
is called a sparse matrix.
We can also use the simple matrix to store the elements in the memory; then why do we need
to use the sparse matrix. The following are the advantages of using a sparse matrix:
o Storage: As we know, a sparse matrix that contains lesser non-zero elements than zero
so less memory can be used to store elements. It evaluates only the non-zero elements.
o Computing time: In the case of searching n sparse matrix, we need to traverse only the
non-zero elements rather than traversing all the sparse matrix elements. It saves
computing time by logically designing a data structure traversing non-zero elements.
Representing a sparse matrix by a 2D array leads to the wastage of lots of memory. The
zeroes in the matrix are of no use to store zeroes with non-zero elements. To avoid such
wastage, we can store only non-zero elements. If we store only non-zero elements, it
reduces the traversal time and the storage space.
Sparse Matrix Representation:
The non-zero elements can be stored with triples, i.e., rows, columns, and value. The
sparse matrix can be represented in the following ways:
• Array Representation/Triplet Representation/3-coulmn representation
• Linked Representation
Triplet Representation of Sparse Matrix :
The 2d array (triplet/3-column) can be used to represent a sparse matrix in which there are
three columns named as:
In this representation, we consider only non-zero values along with their row and column
index values. In this representation, the 0th row stores total rows,total columns and total
non-zero values in the matrix.
In above example matrix, there are only 6 non-zero elements (those are 9, 8, 4,
2, 5, 2) and matrix size is 5×6. we represent this matrix as shown in the above
image. Here the first row in the right-side table is filled with values 5, 6, 6
which indicates that it is a Sparse Matrix with 5 rows and 6 columns and 6 non-
zero elements. Second row is filled with 0, 4, 9 which indicates the value in the
matrix at 0th row and 4th column is 9. In the same way the remaining non-zero
values also follow the similar pattern.
Sparse matrix program:
#include <stdio.h>
int main()
{
int a[10][10],b[10][3],i,j,k=0,m,n;
printf("enter row size and column size of array:");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
+printf("\n");
}
printf("before triplet form:\n");
for(i=0;i<m;i<n)
{
for(j=0;j<n;j++)
{
printf("%d",a[i][j]);
}}
printf("\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[k][0]=i;
b[k][1]=j;
b[k][2]=a[i][j];
k++;
}}}
printf("Triplet form is :\n");
for(i=0;i<k;i++)
{
for(j=0;j<3;j++)
{
printf("%d",b[i][j]);
}
printf("\n");
}
Output:
Sparse matrix Linked List Representation
In linked list representation, linked list data structure is used to represent a sparse matrix. In
linked list representation, each node consists of four fields whereas, in array representation,
there are three fields, i.e., row, column, and value. The following are the fields in the linked
list:
Step 1: List the non-zero elements in the matrix with their row and column index.
Step 2: Create new nodes and put values of row and column index and the value of the
non-zero elements.
Step 3: Point the next pointer of the elements to the next element to form the linked list.
In the above figure, sparse represented in the linked list form. In the node, first field represents the
index of row, second field represents the index of column, third field represents the value and fourth
field contains the address of the next node.