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

Module 3 Notes

This document discusses linked lists and their applications. It defines linked lists and describes how they are represented in memory using nodes that contain a data field and a pointer to the next node. The document outlines common linked list operations like traversing, searching, insertion and deletion. It also discusses different types of linked lists like doubly linked lists, circular linked lists and their applications in representing polynomials and sparse matrices. Key concepts like memory allocation using malloc(), freeing memory using free(), and garbage collection are explained.

Uploaded by

Himanshu Ranjan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

Module 3 Notes

This document discusses linked lists and their applications. It defines linked lists and describes how they are represented in memory using nodes that contain a data field and a pointer to the next node. The document outlines common linked list operations like traversing, searching, insertion and deletion. It also discusses different types of linked lists like doubly linked lists, circular linked lists and their applications in representing polynomials and sparse matrices. Key concepts like memory allocation using malloc(), freeing memory using free(), and garbage collection are explained.

Uploaded by

Himanshu Ranjan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Data structures and Applications [18CS32]

MODULE-3
LINKED LISTS
TOPICS
Linked Lists: Definition, Representation of linked lists in Memory, Memory allocation:
Garbage Collection.
Linked list operations: Traversing, Searching, Insertion, and Deletion.
Doubly Linked lists, Circular linked lists, and header linked lists
Linked Stacks and Queues.
Applications of Linked lists – Polynomials, Sparse matrix representation.
Programming Examples

LINKED LISTS
In this chapter, the list data structure is presented. This structure can be used as the basis for the
implementation of other data structures (stacks, queues etc.). The basic linked list can be used without
modification in many programs. However, some applications require enhancements to the linked list
design. These enhancements fall into three broad categories and yield variations on linked lists that can
be used.
The disadvantages of arrays are:
● The size of the array is fixed. Most often this size is specified at compile time. This makes the
programmers to allocate arrays, which seems "large enough" than required.

● Inserting new elements at the front is potentially expensive because existing elements need to be
shifted over to make room.

● Deleting an element from an array is not possible. Linked lists have their own strengths and
weaknesses, but they happen to be strong where arrays are weak. Generally, arrays allocate the
memory for all its elements in one block whereas linked lists use an entirely different strategy.
Linked lists allocate memory for each element separately and only when necessary.

Here is a quick review of the terminology and rules of pointers. The linked list code will depend
on the following functions:
● malloc() is a system function which allocates a block of memory in the "heap" and returns a pointer
to the new block. The prototype of malloc() and other heap functions are in stdlib.h. malloc() returns
NULL if it cannot fulfill the request. It is defined by: void *malloc (number_of_bytes) Since a void *
is returned the C standard states that this pointer can be converted to mple, any type.

Dept of ISE, RNSIT Page 1


Data structures and Applications [18CS32]

● For ex: char *cp; cp = (char *) malloc (100); Attempts to get 100 bytes and assigns the starting
address to cp. We can also use the sizeof() function to specify the number of bytes. For example, int
*ip; ip = (int *) malloc (100*sizeof(int));

● free() is the opposite of malloc(), which de-allocates memory. The argument to free() is a pointer to
a block of memory in the heap — a pointer which was obtained by a malloc() function. The syntax
is: free (ptr); The advantage of free() is simply memory management when we no longer need a
block.

3.1 LINKED LIST CONCEPTS


A linked list is a non-sequential collection of data items. It is a dynamic data structure. For every data
item in a linked list has a data field which stores the data and there is an associated pointer that would
give the memory location of the next data item in the linked list. The data items in the linked list are not
in consecutive memory locations. They may be anywhere, but the accessing of these data items is easier
as each data item contains the address of the next data item.
DATA LINK

Figure 1: Representation of node

Figure 2: Example of Linked list


Advantages of linked lists: Linked lists have many advantages. Some of the very important advantages
are:
● Linked lists are dynamic data structures. i.e., they can grow or shrink during the execution of a
program.
● Linked lists have efficient memory utilization. Here, memory is not pre-allocated. Memory is
allocated whenever it is required and it is de-allocated (removed) when it is no longer needed.
● Insertion and Deletions are easier and efficient. Linked lists provide flexibility in inserting a data
item at a specified position and deletion of the data item from the given position.
● Many complex applications can be easily carried out with linked lists.

Dept of ISE, RNSIT Page 2


Data structures and Applications [18CS32]

Disadvantages of linked lists:


● It consumes more space because every node requires a additional pointer to store address of the next
node.
● Searching a particular element in list is difficult and also time consuming.
Comparison between array and linked list:

3.2 TYPES OF LINKED LISTS


Basically we can put linked lists into the following four items:
1. Single Linked List.
2. Double Linked List.
3. Circular Linked List.
4. Circular Double Linked List.
● A single linked list is one in which all nodes are linked together in some sequential manner. Hence, it
is also called as linear linked list.
● A double linked list is one in which all nodes are linked together by multiple links which helps in
accessing both the successor node (next node) and predecessor node (previous node) from any
arbitrary node within the list. Therefore each node in a double linked list has two link fields
(pointers) to point to the left node (previous) and the right node (next). This helps to traverse in
forward direction and backward direction.

Dept of ISE, RNSIT Page 3


Data structures and Applications [18CS32]

● A circular linked list is one, which has no beginning and no end. A single linked list can be made a
circular linked list by simply storing address of the very first node in the link field of the last node.
● A circular double linked list is one, which has both the successor pointer and predecessor pointer in
the circular manner.

3.3 SINGLE LINKED LIST:


Singly linked lists are the basic type of linked lists where each node has exactly one pointer field.
A singly linked list is comprised of zero/ more number of nodes when the number of nodes is
zero , the list is empty otherwise if the linked list is non-empty, the list is pictorially represented as 1st
node links to 2nd node and 2nd node links to 3rd node and so on. the last node has zero link whose value
of address is set to NULL.

REPRESENTING SLL IN C LANGUAGE / MEMORY ALLOCATION


The following features are used to represent SLL. Use the following 3 steps to create a SLL.
1. Define node’s structure
To define a node, self-referential structures are used

2. Create a new node


malloc( ) or MALLOC macro is used to allocate memory for the defined structures nodes
of the size needed for structure node considered.

3. Removal of nodes
At any point if the allocated nodes are not in use, they are removed by free( ).
Example: To create a linked list of words following the above steps follow the steps given below.

1. Defining a node

Using self-referential structures nodes are created. for a list of words, in every node the data field should
store words, so define datatype accordingly.
typedef struct listnode *listpointer;
typedef struct
{
char data[4];
listpointer link;
}listNode;
This definition will result into a node by name listNode containing char data field of size 4 and a
field by name link , which is a pointer variable of type listpointer , where listpointer is a pointer to whole
structure.

link

Dept of ISE, RNSIT Page 4


Data structures and Applications [18CS32]

Figure 3: Defining a node


2. Create a new empty list

listpointer first=NULL;
● Here, first is a variable of type pointer i.e. listpointer, initially making it as NULL and hence , a
new list is created by name first and it is empty,

● To create a new node in list, malloc() function is used.

first = malloc( sizeof(*first));


3. To assign the value to the fields of the node. Here, the operator 🡪 is used, which is referred as the
structure member operator.

strcpy(first🡪data,”BAT”);
first🡪link=NULL;
These statements are represented as below:

B A T \0 NULL

Here, B = first🡪 data [ 0 ];


A = first🡪 data [ 1 ];
T = first🡪 data [ 2 ];
\0 = first🡪 data [ 3 ];
NULL=first 🡪 link;

GARBAGE COLLECTION
● When the memory is allocated to the linked lists, a special list is maintained which consists of
unused memory cells. This list, which has its own pointer, is called the list of available space/ the
free storage list or the free pool.

● Thus, the memory is allocated from free pool.

● When node is deleted from a list or a entire list is deleted from a program, the memory space has to
be inserted into free storage list, so that it will be reusable.

● The operating system of a computer may periodically collect all the deleted space onto the
free-storage list. Any technique which does this collection is called garbage collection.

Garbage collection usually takes place in 2 steps:

1. The computer runs through all list, tagging those cells which are currently in use and then the
computer runs through the memory, collecting all untagged space onto the free – storage list.

Dept of ISE, RNSIT Page 5


Data structures and Applications [18CS32]

2. the garbage collection may take place when there is only some minimum amount of space or
no space at all left in the free-storage list or when the CPU is idle and has time to do the
collection

The garbage collection is invisible to the programmer.

LINKED LIST OPERATIONS


The following operations are performed on the linked list

1. INSERTION

Insertion operation is used to insert new node to the list created. This operation is performed
depending on many scenarios of linked lists like

● If the linked list is empty, then new node after insertion becomes the first node.

● If the list already contains nodes the new node is attached either at front end of the list or at the last
end.

● If the insertion is based on the data element/position, then search the list to find the location and then
insert the new node.

NOTE: same conditions are checked for deleting a node from the list as well.

Figure 4: Insertion Operation

Here, if we need to insert the data item GAT between FAT and HAT, the following steps are
followed.
● Get a node temp

● Set the data field to GAT

● Set the link field of temp to point to the node after FAT, which contains HAT

● Set FAT link field to temp

In figure, if we need to delete FAT, then find the element that immediately precedes the element to be
deleted.
EX :- Here, identify EAT.
● Set that element link to the position of GAT i.e. EAT link should point to GAT.

● Use free() to delete FAT node.

Function to create a two-node SLL


listpointer create2()
{
Dept of ISE, RNSIT Page 6
Data structures and Applications [18CS32]

listpointer first,second;
first = malloc(sizeof(*first));
second = malloc(sizeof(*second));
first🡪data=10;
second🡪data=20;
first🡪link=second;
second🡪link=NULL;
return first;
}
C function to insert new node with data value 50 into the SLL by name first after the node X.
void insert(listpointer *first, listpointer X)
{
listpointer temp;
temp=malloc(sizeof(*temp));
temp🡪data = 50;
if(*first)
{
temp🡪 link = x🡪link;
x🡪link = temp;
}
else
{
temp🡪 link = NULL;
*first=temp;
}
}

from main function, call this function as insert( *first , x);

Node to be inserted

temp

● If it is empty, then will be the first node in SLL first.

first🡪

● So, here we are passing the address of first, the second argument is the X.

2. LIST DELETION

Example deletes X from the list first , where trail is the preceding node of X.
void delete( listpointer *first, listpointer trail, listpointer X)

Dept of ISE, RNSIT Page 7


Data structures and Applications [18CS32]

{
if(trail)
trail🡪link = x🡪link;
else
*first = (*first)🡪link;
free(x);
}

From main function call this function as below:-

delete (&first, NULL, first);


OR
delete (&first, y, y🡪link);

● Any node is deleted from a linked list by another function delete.


● Assuming that we have 3 pointers, first which points to the start of the list, x points to the node
that we wish to delete, &trail points to the node that precedes x node

● In this example, the node x , which has to be deleted is the first node itself. so, after deleting that
node, resultant linked list should be like , next figure. so, we must change the value of first to
point to node with data value 50.

● In above example, deletion corresponds to the function call, delete (&first, y, y🡪link); where, y
is the trail node for the deleting node x, which is y🡪link, i.e, the next node after y. so deleting
node containing data 20 is performed and y🡪link set to NULL.

3. TRAVESING/PRINTING THE LIST


To print the data fields of the nodes in a list. First print the contents of first’s data field. Then,
replace first with the address in its link field. So, continue printing out the data field and moving to the
next node until end of the list is reached.
void printlist (listpointer first)
{
printf(“\n The list contains”);
for( ; first ; first🡪link)
printf(“%4d”, first🡪data);
}

3. SEARCHING

Dept of ISE, RNSIT Page 8


Data structures and Applications [18CS32]

● Searching operation performs the process of finding the node containing the desired value in
linked list.
● Searching starts from the first node of the linked list, so that the complete linked list can be
searched to find the element. if found search is successful, else unsuccessful.

void search(listpointer first, int key)


{
int found = 0;
while( first!=NULL && found = = 0)
{
if(first🡪data!=key)
first=first🡪next;
else
found = = 1;
}
}

DOUBLY LINKED LISTS


● Doubly linked list contains the node which contains the following fields: data field and two link
fields, one linking in forward direction and other linking in backward direction.
● figure below shows the DLL

Figure 5: DLL
● In singular linked list, it is possible to traverse in only one direction (forward) in the linked list.
● If we are pointing to a specific node say p, then we can move only in the direction of the links.
● To find a node before p, i.e. preceding node p is difficult unless we start from beginning to reach
its previous node.
● Same problem exists, when delete or insertion operations are done on any arbitrarily node in
SLL.
● These problems can be overcome using DLL, as they have both direction links, from any node p,
where we can find next node/ preceding node easily.

C Representation of DLL

Dept of ISE, RNSIT Page 9


Data structures and Applications [18CS32]

A node in a doubly linked list has at least three fields, a left link field (llink), a data field(data), and a
right link field(rlink).

typedef struct node *nodepointer;


typedef struct
{
nodepointer llink;
element data;
nodepointer rlink;
}node;
if ptr points to a node in a DLL, then ptr=ptr🡪llink🡪rlink= ptr🡪rlink🡪llink;

Operations performed on DLL


1. Insert
It inserts new node to the right of the node.
void dinsert (nodepointer node,nodepointer newnode)
{
newnode🡪llink=node;
node🡪rlink=newnode;
}

Figure 6: Insertion in DLL

2. Deletion
It deleted the node from the list pointed to by node.
void delete(nodepointer node,nodepointer deleted)
{
if(node == deleted)
printf(“\n deletion of header node is not permitted”);
else
{
deleted🡪llink🡪rlink=deleted🡪rlink;
deleted🡪rlink🡪llink=deleted🡪llink;
free(deleted);
}
}

Dept of ISE, RNSIT Page 10


Data structures and Applications [18CS32]

Figure 7: Deletion in DLL


CIRCULAR LINKED LISTS
A linked list whose last node points back to the first node instead of containing a null pointer is
called circular list.
1. Circular singly linked list

Figure 8: CSLL
In a singly linked circular list, the pointer field of the last node stores the address of the starting node In
the list. Hence it is easy to traverse the list given the address of any node in the list.

2. Circular doubly linked list

A doubly linked list whose last node rlink points to first node and first node llink points to last node,
making it is a circular called as circular DLL.

Figure 9: CDLL
To insert a new node into circular DLL at the end
void dinsert(nodepointer node,nodepointer newnode)
{
newnode🡪llink=node;
newnode🡪rlink=node🡪rlink;
node🡪rlink🡪llink=newnode;
node🡪rlink=newnode;
}

Dept of ISE, RNSIT Page 11


Data structures and Applications [18CS32]

Figure 10: Insertion in CDLL


Advantages of CLL
● Linked list made as circular can connect to the first node easily.
● Insertion/deletion operations can be performed quickly.
● Accessing previous node of any node X, can be achieved from X🡪end of the list and end to that
particular node.
● Circular linked list even can be adapted for DLL, which are doubly linked CLL.

HEADER LINKED LIST


A header linked list is a linked list which always contains a special node called the header node
at the beginning of the list. It is an extra node kept at the front of a list. Such a node does not represent
an item in the list. The information portion might be unused.
This header node allows us to perform operations more easily and also differentiaties the
nodes,first/last especially when the list is circular.The header node may contain some useful about linked
list such as number of nodes in the list , address of last node/ some specific distinguishing information .
the address of starting node is refereed by headerpointer.
There are two types of header list
1. Grounded header list: is a header list where the last node contains the null pointer.
2. Circular header list: is a header list where the last node points back to the header node.

Figure 11: Grounded and Circular header Linked Lis


Linked Stacks and Queues:-
● To represent several queues and stacks sequentially, linked list is the efficient way.
● The linked stack and linked queue are pictorially shown below:

Dept of ISE, RNSIT Page 12


Data structures and Applications [18CS32]

Figure 12: (a) Linked Stack and (b) Linked queue


● The directions of arrows in both stack queue representation help us to easily understand the
operations i.e insertion and deletion of nodes. i.e in stack, push/pop operation performed from ht
etop of the stack.
● In Figure (b) above, in linked queue, node is easily inserted and deleted using rear and front
respectively.
● C declarations to represent ‘n’, number of stacks in memory simultaneously, where
n<= MAX_STACKS.

typedef struct
{
int key;
}Element;
typedef struct stack * stackPointer;
typedef struct
{
Element data;
stackPointer link;
}stack;
stackPointer top[MAX_STACKS];
● The initial condition for the stack is top[i]=NULL, 0<i<=MAX_STACKS.
● Boundary condition is top[i]=NULL if the ith stack is empty.

Operations on Mulitple stacks (Linked stack):-


1) PUSH:-
● The push function creates a new node by name temp & places item in the data field & top in the link
field. The variable top is then changed to point to temp.
void push(int i, Element item)
{
stackPointer temp;
temp = malloc(sizeof(*temp));
temp->data = item;
temp->link = tep[i];

Dept of ISE, RNSIT Page 13


Data structures and Applications [18CS32]

top[i] = temp;
}
● The above C function is to add item to the ith stack.
2) POP:-
Element pop(int i)
{
stackPointer temp = top[i];
Element item;
if(!temp)
return stackEmpty();
item = temp->data;
top[i] = temp->link;
free(temp);
return item;
}
● The above C function is used to delete top element from ith stack.

LINKED QUEUES:-
● To represent ‘m’ queues simultaneously, declarations are as follows:- where m<=MAX_QUEUES.
#define MAX_QUEUES 10
typedef struct queue *queuePointer;
typedef struct
{
Element data;
queuePointer link;
}queue;
queuePointer front[MAX_QUEUES], rear[MAX_QUEUES];
● In initial condition for the queue, front[i] = NULL, 0<=i<MAX_QUEUES and the boundary is
front[i] = NULL iff the ith queue is empty.
Operations of Linked queue:-
1) Insert:- add an item to the rear end of a linked queue.
void addq(i, item)
{
queuePointer temp;
temp = malloc(sizeof(*temp));
temp->data = item;
temp->link = NULL;
if(front[i])
rear[i]->link = temp;
else
front[i] = temp;
rear[i] = temp;
}
2) Delete:- Deletes an item from the front of a linked queue.
Element deleteq( int i)
{
queuePointer temp = front[i];
Element item;

Dept of ISE, RNSIT Page 14


Data structures and Applications [18CS32]

if(!temp)
return queueEmpty();
item = temp->dtaa;
front[i] = temp->link;
free(temp);
return item;
}

APPLICATIONS OF LINKED LISTS


1) Polynomial Addition:-
● For adding 2 polynomials, the following terms are compared and checked starting at the nodes
pointed to by a & b.
o If the exponents are equal – add 2 coefficients and create new term for the result.
Move a & b to point to next nodes.
o If the exponent of the term in a is less than the exponent of current item in b, then,
▪ Create a duplicate term b.
▪ Attach this term to the result called c.
▪ Advance the pointer to the next term only in b.
o If the exponent of the term in a is greater then the exponent of curret item in b, then,
▪ Create a duplicate term a.
▪ Attach this term to the result, called c.
▪ Advance the pointer to next term only in a.
Polynomial is represented as:-
A(x) = am-1 x cm-1 + ... +a0xc0
where, ai are non zero co- efficients and the ci are non negative integer exponents such that cm-1 > cm-2
>...>c1>c0>=0.
C Declaration:-
typedef struct polyNode *polyPointer;
typedef struct
{
int coef;
int expon;
polyPointer link;
}polyNode;
polyPointer a, b;
polyNodes looks as:-
coef expon link

a= 3x14+2x8+1, b = 8x14-3x10+10x6
3 14

2 8

1 0

3 10

Dept of ISE, RNSIT Page 15


Data structures and Applications [18CS32]

8 14

10 6

Figure 13: Representaion of a & b polynomials.

C Function for polynomial addition is given below:-


polyPointer padd(polyPointer a, polyPointer b)
{ /* return a polynomial which is the sum of a & b */
polyPointer c, rear, temp;
int sum;
MALLOC(rear, sizeof(*rear));
c=rear;
while(a && b)
switch(COMPARE (a->expon, b->expon))
{
case -1:/* a->expon < b->expon */
attach(b->coef, b->expon, & rear);
b=b->link;
break;
case 0: /*a->expon == b->expon */
sum = a->coef + b->coef;
if(sum)
attach(sum, a->expon, & rear);
a=a->link;
b=b->kink;
break;
case 1: /* a -> expon > b->expon */
attach(a->coef, a->expon, & rear);
a=a->link;
}
/* copy rest of the list a and then list b */
for(;a;a->link)
attach(a->coef, a->expon, & rear);
for(;b;b->link)
attach(b->coef, b->expon, & rear);
rear->link = NULL;
/* delete extra initial node */
temp = c;
c=c->link;
free(temp);
return c;
}
● The above function uses streaming process, that moves along the 2 polynomials, either copying
terms directly / adding them to the result.
● Thus, while loop has 3 cases, depending on whether next pair of elements are =, < or >.
● To create a new node and append it to the end of c, the above addition function uses attach().
Dept of ISE, RNSIT Page 16
Data structures and Applications [18CS32]

void attach( float coefficient, int exponent, polyPointer *ptr)


{ /* create a new node with coef = coefficient & expon = exponent, attach is to the node pointed to
by ptr. ptr is updated to point to this new nodes */
polyPointer temp;
MALLOC(temp, sizeof(*temp));
temp->coef = coefficient;
temp->expon = exponent;
(*ptr)->link = temp;
*ptr = temp;
}

Erasing Polynomials:-
● While using polynomials for different computations, temporary nodes which are having actually
waste data can be erased.
● Example:- For performing e(x) = a(x) * b(x) + d(x);
● Main function is as below:-
polyPointer a,b,d,e;
a=readPoly();
b=readPoly();
d=readPoly();
temp=pmult(a,b);
e=padd(temp,d);
printPoly(e);
● Here, temp is a node, which need to be erased. So, the following function is used to erase nodes.
void erase(polyPointer *ptr)
{
polyPointer temp;
while(*ptr)
{
temp=*ptr;
*ptr=(*ptr)->link;
free(temp);
}
}

Circular list representation of polynomials:-


● In a linked structure, the link of the last node points to the first node in the list, it is called as circular
list.
● Nodes of a polynomial can be freed efficiently if circular list representation is used.

Figure 14: Circular representation of 3x14+2x8+1


● Free nodes that is no longer in use can be reused by maintaining our own list of nodes that have been
freed.

Dept of ISE, RNSIT Page 17


Data structures and Applications [18CS32]

● When we need a new node, freed nodes list is examined, if it is not empty, then use those nodes. If
not, use malloc() to create a new node.
● getNode() & retNode() functions are used to use a node and free the node as malloc() and free().
polyPointer getNode(void)
{
polyPointer node;
if(avail)
{
node=avail;
avail=avail->link;
}
else
MALLOC(node, sizeof(*node));
return node;
}
void retNode(polyPointer node)
{
/*return a node to the available list */
node->link=avail;
avail = node;
}

Erasing Circular list:-


● We can erase circular list in a fixed amount of time independent of the number of nodes in the list
using cerase() function
void cerase(polyPointer *ptr)
{
polyPointer temp;
if(*ptr)
temp=(*ptr)->link;
(*ptr)->link = avail;
avail = temp;
*ptr = NULL;
}
Circular lists with header nodes:-
● In order to handle the zero polynomial, each polynomial with a header node is introduced i.e. each
polynomial zero / non-zero contains 1 additional node.
● The expon & coef fields of this node are irrelavant.

Figure 15: Zero Polynomial

Dept of ISE, RNSIT Page 18


Data structures and Applications [18CS32]

Figure 16: Polynomial 3x14+2x8+1


polyPointer cpadd(polyPointer a, polyPointer b)
{
polyPointer startA, c, lastC;
int sum, done=FALSE;
startA=a;
a=a->link;
b=b->link;
c=getNode();
c->expon = -1, lastC=c;
do
{
switch(COMPARE(a->expon, b->expon))
{
case -1: attach(b->coef, b->expon, &lastC);
b=b->link;
break;
case 0: if(startA == a)
done = TRUE;
else
{
sum=a->coef+b->coef;
if(sum)
attach(sum, a->expon, &lastC);
a=a->link;
b=b->link;
}
break;
case 1: attach(a->coef, a->expon, lastC);
a=a->link;
}
}while(!done);
lastC->link=c;
return c;
}

SPARSE MATRIX:-
● Sparse Matrix is a matrix with more number of zero enteries than non-zero enteries.
● Each non-zero term is represented by a node with 3 fields:- row, column and value.
● Linked list representation for sparse matrix are more efficient than array representation.
● In this represenation, each column of a sparse matrix is represented as a circularly linked list with a
header node.
● Similarly, representation is used for each row of the sparse matirx.
● Each node has a tag field, which distinguish between header nodes and entry nodes. Each header
node has 3 additional fields:- down, right & next.
o down field to link into a column list.
o right field to link into a row list.
o next field links the header nodes together.

Dept of ISE, RNSIT Page 19


Data structures and Applications [18CS32]

● Each element entry node has 3 fields in addition to the tag field:- row, col, down, right value.
o down field to link to next non-zero term in the same column.
o right field to link to next non-zero term in the same row.
● Thus, if aij ≠ 0, there is a node into tag field = entry, value =aij, row=i & cal=j.

C declarations to represent sparse matrix using linked list.


#define MAX_SIZE 50
typedef Enum {head,entry} tagfield;
typedef struct matrixNode *matrixpointer;
typedef struct
{
int row;
int col;
int value;
} entryNode;
typedef struct
{
matrix pointer down;
matrix pointer right;
tag field tag;
union
{
matrix pointer next;
entry nodes entry;
}u;
}matrix Node;
matrix pointer hnode[MAX_SIZE];
The figure shows linked representation of sparse matrix for the following sparse matrix shown
below:-
000060
040000
400800
000004
007000

Dept of ISE, RNSIT Page 20


Data structures and Applications [18CS32]

Figure 17:-Linked representation of the sparse matrix

Sparse Matrix Operations:- Input, Output & Erase.


1. Sparse Matrix Input:-
● The first operation is of reading in a sparse matrix and obtaining it’s linked representation. The
first input line consists of the number of rows, number of columns and the number of non zero
terms. This line is followed by numTerms, lines of input, each of which is of the form:- row, col,
value.
● The sample input for sparse matrix is given below:-
next
down right

row col value


down right

(a) Header Node (b) Element Node


Figure 18:- Node Structure for sparse Matrices
● The function mread first sets up the header nodes & then sets up each row list while
simultaneously building the column lists. The next field of a header node,i,is initially used to
keep track of the last node in column i.
matrixPointer mread(void)

Dept of ISE, RNSIT Page 21


Data structures and Applications [18CS32]

{
/* read in a matrix & sets up its linked representation */
int num Rows,numCols,numTerms,numHead,i;
int row,col,value,currentRow;
matrix pointer temp,last,node;
printf(“enter the number of rows,columns,non-zero terms”);
scanf(“%d%d%d”,&numRows,&numCols,&numTerms);
numHeads=(numcols>numRows) ? numCols:numRows;
node=newNode();
node🡪tag=entry;
node🡪u .entry.row=numRows;
node🡪u.entry.col=numCols;
if(!numHeads)
node🡪right=node;
else
/*initialize the header nodes8/
{
for(i=0;i<numHeads;i++)
{
temp=newNode;
hdnode[i]=temp;
hdnode[i]->tag = head;
hdnode[i]->right = temp;
hdnode[i]->u.next = temp;
}
currentRow = 0;
last = hdnode[0];
for(i=0;i<numTerms;i++)
{
printf(“Enter row, column & value”);
scanf(“%d %d %d”, & row, & col, & value);
if(row>currentRow)
{
last->right = hdnode[currentRow];
currentRow = row;
last=hdnode[row];
}
MALLOC(temp, sizeof(*temp));
temp->tag = entry;
temp->u.entry.row=row;
temp->u.entry.col=col;
temp->u.entry.value=value;
last->right = temp;
hdnode[col]->u.next->down= temp;
hdnode[col]->u.next = temp;
}
last->right = hdnode[currentRow];
for(i=0;i<numCols;i++)
hdnode[i]->u.next->down = hdnode[i];

Dept of ISE, RNSIT Page 22


Data structures and Applications [18CS32]

hdnode[numHeads-1]->u.next=node;
node->right = hdnode[0];
}
return node;
}

2. Sparse Matrix Output:-


To print out the contents of a sparse matrix in a form. The function mwrite is written as below:
void mwrite(matrixPointer node)
{
/*print out the matrix in row major form */
int i;
matrixPointer temp, head=node->right;
printf(“numRows=%d, numCols=%d\n”, node->u.entry.row, node->u.entry.col);
for(i=0;i<node->u.entry.row;i++)
{
for(temp=head->right;temp!=head;temp=temp->right)
printf(“%5d %5d %5d\n”, temp->u.entry.row, temp->u.entry.col,
temp->u.entry.value);
head=head->u.next;
}
}

3. Erasing a Sparse Matrix


To return all the nodes of a sparse matrix to system memory, one at a time using free(), is given
below:-
void merase(matrixPointer * node)
{
matrixPointer x,y,head=(*node)->right;
int i;
for(i=0;i<(*node)->u.entry.row;i++)
{
y=head->right;
while(y!=head)
{
x=y;
y=y->right;
free(x);
}
x=head;head=head->u.next;free(x);
}
y=head;
while(y!=*node)
{ x=y;y=y->u.next;free(x); }
}
free(*node);
*node=NULL;
}

Dept of ISE, RNSIT Page 23


Data structures and Applications [18CS32]

6. Design, Develop and Implement a menu driven Program in C for the following operations
on Circular QUEUE of Characters (Array Implementation of Queue with maximum size
MAX)

a. Insert an Element on to Circular QUEUE

b. Delete an Element from Circular QUEUE

c. Demonstrate Overflow and Underflow situations on Circular QUEUE

d. Display the status of Circular QUEUE

e. Exit

Dept of ISE, RNSIT Page 24


Data structures and Applications [18CS32]

Support the program with appropriate functions for each of the above operations

#include <stdio.h>
#include<stdlib.h>
#define qmax 5
char q[qmax];
int front=0,rear=-1;
void qinsert();
void qdelete();
void qdisplay();

void main()
{
int ch;
printf("\nCircular Queue operations\n");
printf("1.insert\n2.delete\n3.display\n4.exit\n");
while(1)
{
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: qinsert(); break;
case 2: qdelete(); break;
case 3: qdisplay(); break;
case 4: exit(1);
default: printf("Invalid option\n");
}
}
}
void qinsert()
{
char x;
if((front==0&&rear==qmax-1)||(front>0&&rear==front-1))
printf("Queue is overflow\n");
else
{
printf("\nEnter element to be insert:");
scanf("\n%c",&x);
if(rear==qmax-1&&front>0)
{
rear=0;
q[rear]=x;
}
else
{
if((front==0&&rear==-1)||(rear!=front-1))
q[++rear]=x;
}
printf("%c is successfully inserted", x);

Dept of ISE, RNSIT Page 25


Data structures and Applications [18CS32]

}
void qdelete()
{
char a;
if((front==0)&&(rear==-1))
{
printf("Queue is underflow\n");
return;
}
if(front==rear)
{
a=q[front];
rear=-1;
front=0;
}
else if(front==qmax-1)
{
a=q[front];
front=0;
}
else a=q[front++];
printf("Deleted element is:%c\n", a);
}
void qdisplay()
{
int i,j;
if(front==0&&rear==-1)
{
printf("Queue is underflow\n");
return;
}
if(front>rear)
{
for(i=0;i<=rear;i++)
printf("\t%c",q[i]);
for(j=front;j<=qmax-1;j++)
printf("\t%c",q[j]);
printf("\nrear is at %c\n",q[rear]);
printf("\nfront is at %c\n",q[front]);
}
else
{
for(i=front;i<=rear;i++)
printf("\t%c",q[i]);
printf("\nrear is at %c\n",q[rear]);
printf("\nfront is at %c\n",q[front]);
}
printf("\n");
}

Dept of ISE, RNSIT Page 26


Data structures and Applications [18CS32]

7. Design, Develop and Implement a menu driven Program in C for the following operations
on Singly Linked List (SLL) of Student Data with the fields: USN, Name, Branch, Sem, PhNo
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration of stack)
e. Exit

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>

int count=0;

struct node
{
int sem;
char phno[10];
char name[20],branch[20],usn[10];
struct node *next;
}*first=NULL,*last=NULL,*temp=NULL;

void create()
{
int sem;
char name[20],usn[10],branch[20],phno[10];
temp=(struct node *)malloc(sizeof(struct node));

printf("Enter the details \n");


printf("\nName:"); scanf("%s",name); flushall();
printf("\nUSN:"); gets(usn); flushall();
printf("\nBranch:"); gets(branch);
printf("\nSem:"); scanf("%d",&sem);
printf("\nPhone Number:"); scanf("%s",phno);

strcpy(temp->usn,usn);
strcpy(temp->name,name);
strcpy(temp->branch,branch);
strcpy(temp->phno,phno);
temp->sem=sem;
temp->next=NULL;

count++;
}
void deletefront()

Dept of ISE, RNSIT Page 27


Data structures and Applications [18CS32]

{
temp=first;
if(first==NULL)
{
printf("\n list is empty");
return;
}
if(temp->next==NULL)
{
printf("The deleted node is \n");

printf("%s\t%s\t%s\t%d\t%s",temp->name,temp->usn,temp->branch,temp->sem,temp->phno);
free(temp);
first=NULL;
}
else
{
first=temp->next;
printf("The deleted node is \n");

printf("%s\t%s\t%s\t%d\t%s",temp->name,temp->usn,temp->branch,temp->sem,temp->phno);
free(temp);
}
count--;
}
void deleteatend()
{
temp=first;
if(first==NULL)
{
printf("\n list is empty");
return;
}
if(temp->next==NULL)
{
printf("The deleted node is \n");

printf("%s\t%s\t%s\t%d\t%s",temp->name,temp->usn,temp->branch,temp->sem,temp->phno);
free(temp);
first=NULL;
}
else
{
while(temp->next!=last)
temp=temp->next;
printf("The deleted node is \n");
printf("%s\t%s\t%s\t%d\t%s",last->name,last->usn,last->branch,last->sem,last->phno);
free(last);
last=temp;

Dept of ISE, RNSIT Page 28


Data structures and Applications [18CS32]

last->next=NULL;
}
count--;
}
void insertatfirst()
{
create();
if(first==NULL)
{
first=temp;
last=first;
}
else
{
temp->next=first;
first=temp;
}
}
void insertatlast()
{
create();
if(first==NULL)
{
first=temp;
last=first;
}
else
{
last->next=temp;
last=temp;
}
}
void display()
{
if(first==NULL)
{
printf("\n list is empty");
}
else
{
temp=first;
printf("The node is \n");
while(temp!=NULL)
{

printf("%s\t%s\t%s\t%d\t%s--->",temp->name,temp->usn,temp->branch,temp->sem,temp->phno);
temp=temp->next;
printf("\n");

Dept of ISE, RNSIT Page 29


Data structures and Applications [18CS32]

}
printf("\nThe number of nodes in the linked list is %d.",count);
}
}
void main()
{
int ch,i,n;
clrscr();
while(1)
{
printf("\n1.Insert n details student ");
printf("\n2.Insert at beginning");
printf("\n3.Insert at last");
printf("\n4.Delete from begining");
printf("\n5.Delete from last");
printf("\n6.Display");
printf("\n7.Exit");
printf("\nEneter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1 : printf("\nEnter the value of n ");
scanf("%d",&n);
for(i=0;i<n;i++)
insertatfirst();
break;
case 2 : insertatfirst();
break;
case 3 : insertatlast();
break;
case 4 : deletefront();
break;
case 5 : deleteatend();
break;
case 6 : display();
break;
case 7 : exit(1);
default: printf("\n Wrong Input, try again");
}
}
}

8. Design, Develop and Implement a menu driven Program in C for the following operations
on Doubly Linked List (DLL) of Employee Data with the fields: SSN, Name, Dept,
Designation, Sal, PhNo
a. Create a DLL of N Employees Data by using end insertion.
b. Display the status of DLL and count the number of nodes in it
c. Perform Insertion and Deletion at End of DLL

Dept of ISE, RNSIT Page 30


Data structures and Applications [18CS32]

d. Perform Insertion and Deletion at Front of DLL


e. Demonstrate how this DLL can be used as Double Ended Queue
f. Exit

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

int count=0;
struct node
{
struct node *prev;
int ssn;
char phno[10];
char name[20],dept[20],desg[10];
float sal;
struct node *next;
}*first=NULL,*last=NULL,*temp=NULL,*temp1=NULL;

void create()
{
temp=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the employee details: ssn,name,dept,desg,sal,phno");
scanf("%d%s%s%s%f%s",&temp->ssn,temp->name,temp->dept,temp->desg,&temp->sal,temp->phno);
temp->prev=NULL;
temp->next=NULL;
count++;
}
void deleteatfirst()
{
temp=first;
if(first==NULL)
{
printf("\n DLL is empty");
return;
}
if(temp->next==NULL)
{
printf("\nDeleted node is:");

printf("%d\t%s\t%s\t%s\t%f\t%s",temp->ssn,temp->name,temp->dept,temp->desg,temp->sal,temp->ph
no);
free(temp);
first=NULL;
}
else
{
first=temp->next;

Dept of ISE, RNSIT Page 31


Data structures and Applications [18CS32]

printf("\nDeleted node is:");

printf("%d\t%s\t%s\t%s\t%f\t%s",temp->ssn,temp->name,temp->dept,temp->desg,temp->sal,temp->ph
no);
free(temp);
first->prev=NULL;
}
count--;
}
void deleteatlast()
{
temp=first;
if(first==NULL) {
printf("\n DLL is empty");
return;
}
if(temp->next==NULL)
{
printf("\nDeleted node is:");

printf("%d\t%s\t%s\t%s\t%f\t%s",temp->ssn,temp->name,temp->dept,temp->desg,temp->sal,temp->ph
no);
free(temp);
first=NULL;
}
else
{
printf("\nThe deleted node is:");
temp1=last->prev;

printf("%d\t%s\t%s\t%s\t%d\t%s",last->ssn,last->name,last->dept,last->desg,last->sal,last->phno);
free(last);
last=temp1;
last->next=NULL;
}
count--;
}
void insertatfirst()
{
create();
if(first==NULL)
{

first=temp;
last=first;
}
else
{

Dept of ISE, RNSIT Page 32


Data structures and Applications [18CS32]

first->prev=temp;
temp->next=first;
first=temp;
}
}

void insertatlast()
{
create();
if(first==NULL)
{
first=temp;
last=first;
}
else
{
last->next=temp;
temp->prev=last;
last=temp;
}
}
void display()
{
if(first==NULL)
{
printf("\nDLL is empty.");
return;
}
else
{
temp=first;
printf("\n DLL is\n");
while(temp!=NULL)
{

printf("%d\t%s\t%s\t%s\t%f\t%s\n",temp->ssn,temp->name,temp->dept,temp->desg,temp->sal,temp->p
hno);
temp=temp->next;
}
printf("\nThe number of nodes in the linked list is %d.",count);
}
}
void main()
{
int ch,i,n;
clrscr();
while(1)
{

Dept of ISE, RNSIT Page 33


Data structures and Applications [18CS32]

printf("\nEnter the details:");


printf("\n1.Enter n employee details.");
printf("\n2.Insert at beginning.");
printf("\n3.Insert at last");
printf("\n4.Delete at beginning");
printf("\n5.Delete at last");
printf("\n6.Display");
printf("\n7.Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter n value:");
scanf("%d",&n);
for(i=0;i<n;i++)
insertatlast();
break;
case 2:insertatfirst();
break;
case 3:insertatlast();
break;
case 4:deleteatfirst();
break;
case 5:deleteatlast();
break;
case 6:display();
break;
case 7:exit(1);
default:printf("Invalid input.");
}
}
}

Dept of ISE, RNSIT Page 34

You might also like