0% found this document useful (0 votes)
3 views30 pages

ds unit 2

The document provides a comprehensive overview of single linked lists and circular linked lists, detailing their structures, operations (insertion, deletion, display), advantages, and disadvantages. It explains the node structure, types of linked lists, and algorithms for performing various operations on them. Additionally, it highlights the differences in memory usage and traversal between linked lists and arrays.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views30 pages

ds unit 2

The document provides a comprehensive overview of single linked lists and circular linked lists, detailing their structures, operations (insertion, deletion, display), advantages, and disadvantages. It explains the node structure, types of linked lists, and algorithms for performing various operations on them. Additionally, it highlights the differences in memory usage and traversal between linked lists and arrays.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

UNIT-2

Single Linked List and Chain

Single Linked list is a sequence of elements in which every element


has a link to its next element in the sequence. A linked list allocates space for
each element separately in its own block of memory called a "node". The
front of the list is a pointer to the “head/start” node. The single linked list
is called as linear list or chain.

 In any single linked list, the individual element is called as "Node".


 Every "Node" contains two fields, data and next.
 The data field is used to store actual value of that node.
 Next field is used to store the address of the next node in the sequence.
Example :

Structure of Node
struct Node
{
int data;
struct Node *next;
};
Example:

 First node is always reference as "head" or "start".


 Always next part of the last node must be NULL.
Linked List
Types of Linked List
1. Singly or Chain Linked List.
2. Doubly or Two Way Linked List.
3. Circular Linked List.
4. Circular Doubly Linked List.
Operations of Linked List
1. Insertion
2. Deletion
3. Display / Traverse
Insertion operation on Single Linked
List
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
Algorithm for 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 and newNodenext as NULL.
 Step 2: Check whether linked list is Empty (head == NULL)
 Step 3: If it is Empty then, set head = newNode.
 Step 4: If linked list is Not Empty then,
set newNodenext = head and head = newNode.

Algorithm for 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
set 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 (while tempnext != NULL).
 Step 6: Set tempnext = newNode.

Algorithm for Inserting At Specific location in linked list


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 and set
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 node
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.
 Step 7: Finally, Set 'newNodenext = tempnext' and
'tempnext = newNoe
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
 Step 6: If it is FALSE then set head = head->next, and delete temp.

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 'temp' and
'Prev' and initialize 'temp' with head.
 Step 4: Check whether list has only one Node (temp->next == NULL)
 Step 5: If it is TRUE. Then, set head = NULL and delete temp. And
terminate the function.
 Step 6: If it is FALSE. Then, set 'Prev = temp ' and move temp to its next
node. Repeat the same until it reaches to the last node in the list.
(while tempnext != NULL)
 Step 7: Finally, Set Prevnext = NULL and delete temp.

Deleting a Specific Node from the list


We can use 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 'temp' and 'Prev'
and initialize 'temp' with head.
 Step 4: set 'Prev = temp ' and move temp to its next node. Repeat the same
until it reaches to 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 is not possible!!!'. And terminate the function.
 Step 6: If it is reached to the exact node which we want to delete, then
check whether element to be deleted is first node, then
set head = NULL and delete temp.
 Step 7: If temp is not first node then set Prevnext = tempnext and
delete temp.

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 end of linked list.
 Step 5: Finally display NULL.

Advantages of Linked List


Dynamic Data Structure
Linked list is a dynamic data structure so it can grow and shrink at runtime by
allocating and de-allocating memory. So there is no need to give initial size of
linked list.
Insertion and Deletion are easy
Insertion and deletion of nodes are really easier. Unlike array here we don’t have
to shift elements after insertion or deletion of an element. In linked list we just
need to update the address of next pointer of a node.
No Memory Wastage
As size of linked list can increase or decrease at run time so there is no memory
wastage. In case of array there is lot of memory wastage, like if we declare an
array of size 10 and store only 6 elements in it then space of 4 elements are
wasted. There is no such problem in linked list as memory is allocated only when
required.
Implementation is easy
Data structures such as stack and queues can be easily implemented using linked
list.
Disadvantages of Linked List
Memory Usage
More memory is required to store elements in linked list as compared to array.
Because in linked list each node contains a pointer and it requires extra memory.
Traversal
Elements or nodes traversal is difficult in linked list. We can not randomly access
any element as we do in array by index. For example if we want to access a node
at position n then we have to traverse all the nodes before it. So, time required to
access a node is large.
Reverse Traversing
In linked list reverse traversing is really difficult. In case of doubly linked list its
easier but extra memory is required for back pointer hence wastage of memory.
Circular List /Circular Linked List

Circular Linked list is a sequence of elements in which every element


has a link to its next element in the sequence and last element has a link to first
element in the sequence.

Operations of Circular Linked List


1. Insertion
2. Deletion
3. Display
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
following are the 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 .
Step 4: If it is Not Empty then, define a Node temp' and initialize with 'head'.
Step 5: Keep moving the 'temp' to its next node until it reaches to the last node
(while 'temp next != head').
Step 6: Set 'newNodenext =head', 'head = newNode' and 'tempnext = head'.
Inserting At End of the list
following are the 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 (while temp next != head).
Step 6: Set tempnext = newNode and newNodenext = head.

Inserting At Specific location in the list (After a Node)


Following are the 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 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.
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 set newNodenext = tempnext and
tempnext=newNode.
Deletion
In a circular linked list, the deletion operation can be performed in three ways.
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
following steps are used to delete a node from beginning of the circular 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 'temp' and 'last' and
initialize both 'temp' and 'last’ with head.
Step 4: Check whether list is having only one node (headnext == head)
Step 5: If it is TRUE then set head = NULL and delete temp (Setting Empty list
conditions)
Step 6: If it is FALSE move the last until it reaches to the last node.
(while lastnext != head )
Step 7: Then set head = head next, lastnext = head and delete temp.

Deleting from End of the list


following steps are used 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 'temp' and 'prev' and
initialize 'temp' with head.
Step 4: Check whether list has only one Node (head next == head)
Step 5: If it is TRUE. Then, set head = NULL and delete temp. And terminate
from the function. (Setting Empty list condition)
Step 6: If it is FALSE. Then, set 'prev = temp ' and move temp to its next node.
Repeat the same until temp reaches to the last node in the list.
(until temp  next == head)
Step 7: Set prev next = head and delete temp.
Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the circular 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“.
Step 3: If it is Not Empty then, define two Node pointers 'temp' and 'prev' and
initialize 'temp' with head.
Step 4: Keep moving the temp until it reaches to the exact node to be deleted
or to the last node. And every time set 'prev=temp' before moving the
'temp' 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 (headnext== head)
Step 7: If list has only one node and that is the node to be deleted then
set head = NULL and delete 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 set prev= head and keep moving prev to
its next node until prev reaches to the last node. Then
set head=head-->next, prev next = head and delete temp.
Step 10: If temp is not first node then check if it is last node(temp next ==
head).
Step 11: If temp is last node then set prevnext = head and delete temp.
Step 12: If temp is not first node and not last node then
set prevnext = temp next and delete temp.

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 & NULL.

AVAILABLE SPACE LISTS


The collection of free nodes present in the memory is called list of
available space or avail list or free pool or storage pool or simply avail. If we
want to insert a node into the linked list we take a node from this avail list.
If a node is deleted then that node is added to the avail list. Here AVAIL is a
pointer that points to the first node of the free list.
The function getnode(), like new() in C++, returns a pointer to a
newnode taken from the available space list and also removes this node from
the available space list. It is defined as
if(AVAIL ==NULL)
then empty list
return
else
x = AVAIL;
AVAIL = AVAIL -> next;
return x

The function release(), like delete() in C++, causes the node pointed to
by x to be returned to the available space list. It is defined as
x -> next = AVAIL;
AVAIL = x;

Linked Stack / Stack using Linked


List
The major problem with the stack implemented using array is, it
works only for fixed number of data values. Stack implemented using linked list
works for variable size of data.
In linked list implementation of a stack, every new element is
inserted at 'top' and deleted element at ‘top’.

Operations
1. Push
2. Pop
3. display
push(value) - Inserting an element into the Stack
We can use the following steps to insert a new node into the stack...
Step 1: Create a newNode with given value.
Step 2: Check whether stack is Empty (top == NULL)
Step 3: If it is Empty, then set newNode  next = NULL.
Step 4: If it is Not Empty, then set newNode  next = top.
Step 5: Finally, set top = newNode.

pop() - Deleting an Element from a Stack


We can use the following steps to delete a node from the stack...
Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display "Stack is Empty!!! Deletion is not
possible!!!" and terminate the function
Step 3: If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4: Then set 'top = top  next'.
Step 7: Finally, delete 'temp' (free(temp)).

display() - Displaying stack of elements


We can use the following steps to display the elements (nodes) of a stack...
Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display 'Stack is Empty!!!' and terminate the
function.
Step 3: If it is Not Empty, then define a Node pointer 'temp' and initialize
with top.
Step 4: Display 'temp  data --->' and move it to the next node. Repeat the
same until temp reaches to the first node in the stack (temp -->
next != NULL).
Step 4: Finally! Display 'temp  data ---> NULL'.

Queue using Linked List/ Linked Queue

The major problem with the Queue implemented using array is, it
works only for fixed number of data values. Queue implemented using linked list
works for unlimited number of values.
In linked list implementation of a queue, the last inserted element is
always pointed by ‘Rear’ and first inserted element is always pointed by ‘Front’ .

Operations
1. enQueue 2. deQueue 3. display
enQueue(value) - Inserting an element into Queue
We can use the following steps to insert a new node into the queue...
 Step 1: Create a newNode with given value, set 'newNode→next' to NULL.
 Step 2: Check whether queue is Empty (rear == NULL)
 Step 3: If it is Empty then, set front = newNode and rear = newNode.
 Step 4: If it is Not Empty then, set rearnext = newNode
and rear = newNode.

deQueue() - Deleting an Element from Queue


We can use the following steps to delete a node from the queue...
 Step 1: Check whether queue is Empty (front == NULL).
 Step 2: If it is Empty, then display "Queue is Empty!!! Deletion is not
possible!!!" and terminate from the function.
 Step 3: If it is Not Empty then, define a Node pointer 'temp' and set it to
'front'.
 Step 4: Then set 'front = front next' and delete 'temp'.

display() - Displaying the elements of Queue


We can use the following steps to display the elements (nodes) of a queue...
 Step 1: Check whether queue is Empty (front == NULL).
 Step 2: If it is Empty then, display 'Queue is Empty’ & terminate the
function.
 Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize
with front.
 Step 4: Display 'tempdata ' and move it to the next node. Repeat the
same until 'temp' reaches to 'rear' (temp  next !=NULL).
 Step 5: Display 'temp  data  NULL'.

Polynomial & Representation

A polynomial is an expression that consisting of variables,


coefficients and non-negative integer exponents that involves only the operations
of addition, subtraction, multiplication.
Examples
x2 − 4x + 7
x3 + 2x2 + 5x - 1

Polynomials contain three types of forms


1) Monomial :- A polynomial with one term is called monomial
Ex:- 2x2
2) Binomial :- A polynomial with two term is called binomial
Ex:- 5x-1
3) Trinomial :- A polynomial with three term is called trinomial
Ex:- 5x2-2x+8
Structure of Polynomial
struct polynomial
{
int coefficient, power;
struct polynomial *next;
};
Polynomial Addition

Adding two polynomials using Array


It is straight forward method, since both the arrays may be added up
element wise beginning from 0 to n-1, resulting in addition of two
polynomials.
Adding two polynomials using linked list
It requires comparing the exponents, and whenever the exponents
are found to be same, the coefficients are added up. For terms with
different exponents, the complete term is simply added to the result
thereby making it a part of addition result. The complete program to
add two polynomials is given in subsequent section.

Algorithm to add two polynomials using linked list

Let p and q be the two polynomials represented by the linked list.


1. While p and q are not null, repeat step 2.
2. If powers of the two terms are equal then
the sum of the coefficients into the resultant Polynomial
Move p to next
Move q to next
Else if the power of the first polynomial> power of second polynomial
Then insert the term from first polynomial into resultant polynomial
Move p to next
Else insert the term from second polynomial into resultant polynomial
Move q to next.
3. Copy the remaining terms from non empty polynomial into resultant
polynomial.

Program
#include<stdio.h>
#include<stdlib.h>
struct Polynomial
{
int exp,coef;
struct Polynomial *next;
};
typedef struct Polynomial * Poly;
Poly read();
void disp(Poly);
Poly add(Poly,Poly);

Poly read()
{
Poly head=NULL, temp, newNode;
int exp,coef;
char ch;
do
{
printf("\nEnter exponent, coefficient");
scanf("%d%d",&exp,&coef);
newNode=(Poly)malloc(sizeof(Poly));
newNode->exp=exp;
newNode->coef=coef;
newNode->next=NULL;
if( head==NULL )
head=newNode;
else
{
temp=head;
while( temp->next!=NULL )
temp=temp->next;
temp->next=newNode;
}
printf("\nDo you want to continue");
scanf(" %c",&ch);
}while( ch!='n' );
return head;
}
void disp(Poly head)
{
printf("\nPolynomial is \t");
while( head!=NULL )
{
printf(" %+dX^%d",head->coef,head->exp);
head=head->next;
}
}
Poly add(Poly head1,Poly head2)
{
Poly head3=NULL,temp,newNode;
while( head1!=NULL && head2!=NULL )
{
newNode=(Poly)malloc(sizeof(Poly));
if( head1->exp==head2->exp )
{
newNode->exp=head1->exp;
newNode->coef=head1->coef + head2->coef;
head1=head1->next;
head2=head2->next;
}
else if( head1->exp>head2->exp )
{
newNode->exp=head1->exp;
newNode->coef=head1->coef;
head1=head1->next;
}
else if( head1->exp<head2->exp )
{
newNode->exp=head2->exp;
newNode->coef=head2->coef;
head2=head2->next;
}
newNode->next=NULL;
if( head3==NULL )
head3=newNode;
else
{
temp=head3;
while( temp->next!=NULL )
{
temp=temp->next;
}
temp->next=newNode;
}
}
return head3;
}
void main()
{
Poly head1,head2,head3;
head1=read();
head2=read();
head3=add( head1,head2);
disp(head1);
disp(head2);
disp(head3);
}
Circular List Representation of Polynomials

Circular list representation of polymorphism is a sequence of


elements (coefficient & power) in which every element has a link to its next
element in the sequence and last element has a link to first element in the
sequence.

Program
#include <stdio.h>
#include <conio.h>
#include <math.h>
struct Node
{
int exp;
int coef;
struct Node *next;
};
typedef struct Node Node;
Node * create();
void disp(Node *);
Node *create()
{
Node *head=NULL,*temp,*newNode;
int exp,coef;
char ch;
do
{
printf("\nEnter exponent, coefficient");
scanf("%d%d",&exp,&coef);
newNode=(Node *)malloc(sizeof(Node));
newNode->exp=exp;
newNode->coef=coef;
newNode->next=NULL;
if( head==NULL )
{
head=newNode;
head->next=head;
}
else
{
temp=head;
while( temp->next!=head )
temp=temp->next;
temp->next=newNode;
newNode->next=head;
}
printf("\nDo you want to continue");
scanf(" %c",&ch);
}while( ch!='n' );
return head;
}
void disp(Node *head)
{
Node *temp=head;
printf("\nPolynomial is \t");
while( temp!=NULL )
{
printf(" %+dX^%d",temp->coef,temp->exp);
temp=temp->next;
if( temp==head )
break;
}
}
void main()
{
Node *head=NULL;
clrscr();
head=create();
disp(head);
}

EQUIVALENCE CLASSES
A relation ≡, over a set S, is said to be equivalence relation over S if
and only if it is reflexive, symmetric and transitive over S.
1. for any polygon x, x ≡ x, x is electrically equivalent to itself then ≡is
reflexive.
2. for any two polygons(x,y), x ≡ y implies y ≡ x then the relation ≡ is
symmetric
3. for any 3 polygons(x,y,z), x≡y, y≡z implies x≡z then the relation ≡ is
transitive
The examples of equivalence relations are numerous. For example
“equal to” relationship is an equivalence relation.
1. x ≡ x
2. x ≡ y implies y ≡ x
3. x ≡ y, y ≡ z implies x ≡ z
The equivalence relation is to partition set “S” into equivalent classes
such that the two members x and y of “S” are in the same equivalence class
if and only if x ≡ y. For example there are 12 variables numbered from 1 to
12 with pairs as follows:
1 ≡ 5, 4 ≡ 2, 7 ≡ 11, 9 ≡ 10, 8 ≡ 5, 7 ≡ 9, 4 ≡ 6, 3 ≡ 12 and 12 ≡ 1
The equivalence classes over the equivalence relation is as follows. The
12 variables partitioned into 3 classes.
{ 1, 3, 5, 8, 12}, { 2, 4, 6}, { 7, 9, 10, 11}
The algorithm for equivalence classes defined works in two phases. In
the first phase the equivalence pair (i,j) are read and stored. In second
phase, we begin at 1 and find all pairs of (1,j). The values 1 and j are in the
same class. By transitivity, all the pairs of the form (j, k) implies k is in the
same equivalence class.
void equivalence()
{
initialize;
while(there are more pairs)
{
read the next pair (i,j);
process this pair;
}
initialize the output;
do
{
output a new equivalence class;
}while(not done);
}
The inputs n and m represents number of objects and number of
related pairs. The data structure used here is array to hold these pairs. As
we have problem of using arrays we go linked lists. Each node will have data
and next parts. We will use largest one dimensional array seq(n) and
outputting the object we need out(i).
void equivalence()
{
initialize seq to null and out to true;
while(there are more pairs)
{
read the next pair (i,j);
put j on the seq(i) list;
put i on the seq(j) list;
}
for(i= 0; i<n; i++)
if(out(i))
{
out(i) = false;
output this equivalence class;
}
}
SPARSE MATRIX
“A matrix that contains very few number of non-zero elements is
called sparse matrix”
or
“A matrix that contains more number of zero values when compared
with non-zero values is called a sparse matrix”
Sparsematrix Abstract Data Type
{
instances:
a set of triples (row, col, value) where row, col are two
integers and value comes from the set item.
operations:
for all a, b ϵ sparse matrix, x ϵ item, i,j, maxcol, maxrow ϵ
index
sparsematrix create(maxrow, maxcol);
sparesematrix matrixtranspose(a);
psparsematrix matrixadd(a, b);
sparsematrix matrixmultiply(a, b);
}
SPARSE MATRIX REPRESENTATION
For linked representation, we need two types of Node.
1. Header Node / Head Node
2. Element Node

The matrix representation or Triplet Representation of sparse matrix


is shown below for example.
In the above matrix representation there are 5 rows, 6 columns and 6
non-zero values. The linked representation is as follows:

Doubly Linked List

Double linked list is a sequence of elements in which every element


has links to its previous element and next element in the sequence. 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

Here
'link1' stores the address of the previous node
'link2' stores the address of the next node
data' stores the value of that node.
Note
 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
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
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
following steps used to insert new node at beginning of double linked list...
Step1: Create a newNode with given value, set newNodeleft and
newNoderight as NULL.
Step2: Check whether list is Empty (head == NULL)
Step3: If it is Empty then, set head=last=newNode.
Step4: If it is not Empty then, set
newNoderight=head,
headleft=newNode,
head=newNode.

Inserting At End of the list


We can use the following steps to insert a new node at end of double linked
list...
Step1: Create a newNode with given value, set newNodeleft and
newNoderight as NULL.
Step2: Check whether list is Empty (head == NULL)
Step3: If it is Empty, then set head=last=newNode.
Step4: If it is not Empty, then, set
last->right=newNode;
newNode->left=last;
last=newNode;
Inserting At Specific location in the list (After a Node)
We can use following steps to insert new node after node in double linked list...
Step 1: Create a newNode with given value, set newNodeleft and
newNoderight as NULL.
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty then, set
head=last=newNode;
Step 4: If it is not Empty then, define two node pointers prev & temp and
initialize temp with head.
Step 5: perform following until it reaches to the node after which we want to
insert.
prev=temp
temp=temp->next
Step 6: finally assign
Prev->right=newNode;
newNode->left=prev;
newNode->right=temp;
temp->left=newNode;

Deletion
In a double linked list, the deletion operation can be performed in three
ways
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 following steps to delete node from beginning of 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 (headright==NULL)
Step 5: If it is TRUE, then set head=NULL and delete temp
Step 6: If it is FALSE, then set head=tempright, headleft=NULL and delete
temp.

Deleting from End of the list


We can use the following steps to delete a node from end of 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 two Node pointers ‘prev’, 'temp' and
initialize with head.
Step 4: Check whether list has only one Node (headright==NULL)
Step 5: If it is TRUE, then set head=NULL, last=NULL and delete temp
Step 6: If it is FALSE, then keep moving prev and temp until it reaches to the
last node in the list. (while tempright!=NULL)
Step 7: set prev->right=NULL and delete temp.

Deleting a Specific Node from the list


We can use the following steps to delete specific node from 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 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 or not
Step 7: If list has only one node and that is the node which is to be deleted
then set head=NULL and delete 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
head = headright,
headleft=NULL,
free(temp)
Step 10: If temp is not the first node, then check whether it is the last node in
the list (tempright == NULL).
Step 11: If temp is the last node then set
prevRIGHT=NULL
free(temp).
Step 12: If temp is not the first node and not the last node, then
set prevright=tempright
temprightleft=prev
delete 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 and NULL

Generalized List
Generalized list is a series of N elements. In Generalized list a node can have
either an atom or piece of information or sub list.
Conventions for Generalized Lists:
– List names are represented in capital letters
– Atom names are lowercase letters
Definitions for Generalized Lists:
Length – Number of elements (atoms or sub lists) in the list
Head – First element of the list
Tail – List composed of all elements except first of list
Examples of Generalized Lists:
1) A=()
Length=0
A is Null List
2) B=(a,b,c)
Length=3
Head=a
Tail=b,c
3) C=(a,(b,c))
Length=2
Head=a
Tail=(b,c)
Node representation:
– A node in the list needs to have either an atom or piece of
information or pointer to another list
Tag = TRUE/FALSE Data/DLink Link (Next)

Tag = represents type of node


– Tag = false or 0 means holds atomic data
– Tag = true or 1 means holds list of data
• Data
– If Tag = false, hold real data
– If Tag = true, pointer to head of data list
• Link
– Pointer to next item/node in list
Syntax :
struct GeneralListNode
{
int tag;
union GeneralList
{
char data;
GeneralListNode *dlink;
};
GeneralListNode *next;
}
Graphical Representation of Generalized Linked List
A=(a,(b,c))
here
Length=2
Head=a
Tail=(b,c)

false a true 0

A.Front

false b false c 0

RECURSIVE ALGORITHMS FOR LISTS


When a data object is defined recursively, it is easy to describe recursive
algorithms that work on the data objects recursively. A recursive algorithm
consists of two components. The first one is the recursive function itself
called workhorse and the second one is the function that call the recursive
function at the top level is called driver.
When a recursive is used to implement a class operation, we require
two class member functions. The driver is declared as public member
function and workhorse is declared as a private member function. The
different types of recursive algorithms are
1. Copying a list – produces an exact copy of a non-recursive list “l” in
which no sublists are shared.
driver
void genlist :: copy(const genlist &l)
{
first = copy(l, first);
}
workhorse
genlistnode *genlist :: copy(genlistnode *p)
{
genlistnode *q = 0;
if(p)
{
q = new genlistnode;
q -> tag = p -> tag;
if(!p -> tag)
q -> data = p -> data;
else
q -> dlink = copy(p -> dlink);
q -> link = copy(p -> link);
}
return q;
}

2. List Equality – determines whether two lists are identical or not. To be


identical, the lists must have same structure and same data in
corresponding data members.
driver
int operator ==(const genlist &l, const genlist &m)
{
return equal(l, first, m, first);
}
workhorse
int equal(genlistnode *s, genlistnode *t)
{
int x;
if((!s) &&(!t))
return 1;
if(s && t &&(s -> tag == t -> tag))
{
if(!s -> tag)
if(s -> data == t -> data)
x = 1;
else
x = 0;
else
x = equal(s -> dlink, t -> dlink);
if(x)
return equal(s -> link, t -> link);
}
return 0;
}

3. List Depth – computes the depth of the list. if the list is empty then the
depth of the list is zero.
0 if s is an atom
depth(s) = 1 + max{ depth(x1, x2 ….. xn)} if s is the list (x1, x2, …..xn)
driver
int genlist :: depth()
{
return depth(first);
}
workhorse
int genlist :: depth(genlistnode *s)
{
if(*s)
return 0;
genlistnode *p = s;
int m = 0;
while(p)
{
if(p -> tag)
{
int n = depth(p -> dlink);
if(m < n)
m = n;
}
p = p -> link;
}
return m + 1;
}

REFERENCE COUNT, SHARED AND RECURSIVE LISTS


When lists are allowed to be shared by other lists and when recursive
lists are permitted we have some problems. Sharing of sublists can gain
storage space. A sublist in the list can be named. For example, A = (a, (b,
c)),the sublist (b, c) could be assigned the name Z by writing A = (a, Z(b, c)).
For consistency, we write A(a, Z(b, c)).

Lists that are shared by other lists such as A create problems when
we add or delete a node at the front. If the first node is deleted then the
change of the pointers from B to point to second node. If the newnode is
added then pointers from B now should point to the newnode. But we do not
all the points from which a particular list is referenced. The problem can be
easily solved by using head node. The use of head node when performing
add or delete at the front of the lists will eliminate the need to retain all
pointers to a specific list. If each list have head nodes then
The values in the data field of the head node is the reference count of
the corresponding list. when the lists are shared by other lists we need a
mechanism to determine whether or not the list of nodes may be physically
returned to available space list. This mechanism provides reference count
maintained in the head node of each list. Since the data field of the head
node is free the reference count is maintained in this field. The reference
count is the number of pointers to that list.

1. ref(x) = 1, accessible only via x.


2. ref(y) = 3, pointed to by y and two pointers from z
3. ref(z) = 1, accessible only via z
4. ref(w) = 2, accessible via w and a pointer to itself.

When reference count decreases and becomes zero then all the nodes
are physically returned to the available space list. the class definition for
genlist is unchanged and genlistnode is as follows:
enum tag {0, 1, 2};
class genlistnode
{
Friend class genlist;
genlistnode *link
int tag t;
union
{
char data;
genlistnode *dlink;
int ref;
};
};
A recursive algorithm for erasing the list will examine all the top level
nodes of the list whose reference count has become zero. So any such
sublist found, using erase algorithm we erase the list and link it to available
space list. For any recursive list the reference count never becomes zero.

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