UNIT I
UNIT I
CHAPTER - 1 : LISTS
Introduction to Data Structure
Definition: The data structure can be defined as the collection of elements and all the
possible operations which are required for those set of elements. In other words data structure
will tell us the required elements as well as the legal operations on those set of elements.
For example:
Consider a set of elements which are required to store in an array. Various operations such as
reading of the elements and storing them at appropriate index can be performed. If we want
to access any particular element then that element can be retrieved from the array. Thus
reading, printing, searching would be the operations required to perform these tasks for the
elements. Thus data object integer elements and set of operations form the data structure-
array.
Types of Data Structures
The data structures can be divided into two basic types Primitive data structure and Non-
primitive data structure. The Fig. 1.1.1. shows various types of data structures.
Linear data structures are the data structures in which data is arranged in a list or in a straight
sequence.
For example
Arrays, List
Non linear data structures are the data structures in which data may be arranged in
hierarchical manner.
For example
Trees, Graphs
he abstract data type is a triple of D - Set of domains, F - Set of functions, A - Axioms in
which only what is to be done is mentioned but how is to be done is not mentioned.
Abstract Data Types (ADT)
The abstract data type is a triple of D - Set of domains, F - Set of functions, A - Axioms in
which only what is to be done is mentioned but how is to be done is not mentioned.
In ADT, all the implementation details are hidden. In short
ADT = Type + Function names + Behavior of each function
ADT Operations
• While modeling the problems the necessary details are separated out from the unnecessary
details. This process of modeling the problem is called abstraction. It is represented by Fig.
1.2.1.
• The model defines an abstract view to the problem. Thus the model focuses only on
problem related stuff and that you try to define properties of the problem.
• These properties include
i) The data which are affected and
ii) The operations which are identified
• In ADT the implementation details are hidden. Hence the ADT will be-
AbstractDataType List
{
Instances: List is a collection of elements which are arranged in a linear manner.
Operations: Various operations that can be carried out on list are -
1. Insertion: This operation is for insertion of element in the list.
2. Deletion: This operation removed the element from the list.
3. Searching: Based on the value of the key element the desired element can be searched.
4. Modification: The value of the specific element can be changed without changing its
location.
5. Display: The list can be displayed in forward or in backward manner.
}
• The List can be implemented by two ways
1. Array based implementation.
2. Linked List based implementation.
Let us discuss these in detail.
The linked list that can be represented by arrays is called static linked list.In this section we
will discuss in detail how exactly the list can be represented using arrays.Basically list is a
collection of elements.
Array based Implementation
• The linked list that can be represented by arrays is called static linked list.
• In this section we will discuss in detail how exactly the list can be represented using arrays.
• Basically list is a collection of elements.
• To show the list using arrays we will have 'data' and 'link' fields in the array.
• The array can be created as array of structure as
struct node
{
int data;
int next;
} a[10];
• For instance: Consider a list of (10,20,30,40,50). We can store it in arrays as :
Now using for loop we will search 'temp' in array 'a'. When we get the value 'temp' we will
come out of loop by using break statement and check for whether the next location is empty
or not.
The list after insertion of 21 will look like this
3. Deletion of a node
While deleting a node from the list we simply manipulate the next pointer of previous node in
the list. And the data field of the node to be deleted is initialized to - 1.
Consider that the list is
Let us see a C program based on it
Implementation of various List operations using arrays
************
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include<conio.h>
/*data structure for list using array*/
struct node
{
int data;
int next;
}a[10];
void main()
{
char ans;
int i,head, choice;
int Create();
void Display(int);
void Insert();
void Delete();
void Search();
do
{
clrscr();
printf("\n Main Menu");
printf("\n1. Creation");
printf("\n2. Display");
printf("\n3. Insertion of element in the list");
printf("\n4. Deletion of element from the list");
printf("\n5. Searching of element from the list");
printf("\n6. Exit");
printf("\n Enter Your choice");
scanf("%d", &choice);
switch(choice)
{
case 1:for(i=0;i<10;i++)
{
a[i].data = -1;
}
head=Create();
break;
case 2:Display(head);
break;
case 3:Insert();
break;
case 4:Delete();
break;
case 5:Search();
break;
case 6:exit(0);
}
printf("\n Do you Wish to go to Main Menu?");
ans=getch();
} while (ans=='y' || ans == 'Y');
getch();
int Create()
{
int head,i;
printf("\n Enter the index for first node");
scanf("%d", &i);
head=i;
while(i!= -1)
{
printf("\n Enter the data and index of the first element");
scanf("%d %d",&a[i].data,&a[i].next);
i=a[i].next;
}
return head;
}
void Display(int i)
{
printf("(");
while(i!= -1)
{
if(a[i].data==-1)
printf(" ");
else
{
printf("%d, ",a[i].data);
}
i=a[i].next;
}
printf(" NULL)");
}
void Insert()
{
int i,new_data,temp;
printf("\n Enter the new data which is to be inserted");
scanf("%d", &new_data);
printf("\n Enter the data after which you want to insert");
scanf("%d", &temp);
for(i=0;i<10;i++)
{
if(a[i].data==temp)
break;
}
if(a[i+1].data==-1)/*next location is empty*/
{
a[i+1].next=a[i].next;
a[i].next=i+1;
a[i+1].data=new_data;
}
}
void Delete()
{
int i,temp,current,new_next;
printf("\n Enter The node to be deleted");
scanf("%d", &temp);
for(i=0;i<10;i++)
{
if(a[i].data==temp)
{
if(a[i].next==-1)
{
a[i].data=-1;/*writing -1 means deleting the element*/
}
current=i;/*marking the index of an array at which record is placed*/
new_next=a[i].next;/*storing the next pointer value at that index*/
}
}
for(i=0;i<10;i++)
{
if(a[i].next== current)
{
a[i].next=new_next;
a[current].data = -1;
}
}
}
void Search()
{
int i,temp,flag=0;
printf("\n Enter the node to be searched ");
scanf("%d", &temp);
for(i=0;i<10;i++)
{
if(a[i].data==temp)
{
flag=1; /*flag 1 means the element is present*/
break;
}
}
if(flag==1)
printf("\n The %d node is present in the list",temp);
else
printf("\n The node is not present ");
Output
Main Menu
1. Creation
2. Display
3. Insertion of element in the list
4. Deletion of element from the list
5. Searching of element from the list
6. Exit
Enter Your choice1
Enter the index for first node4
Enter the data and index of the first element10 1
Enter the data and index of the first element20 6
Enter the data and index of the first element30 7
Enter the data and index of the first element40 -1
Do you Wish to go to Main Menu?
Main Menu
1. Creation an amouf
2. Display
3. Insertion of element in the list
4. Deletion of element from the list
5. Searching of element from the list
6. Exit
Enter Your choice2
(10, 20, 30, 40, NULL)
Do you Wish to go to Main Menu?
Main Menu
1. Creation
2. Display
3. Insertion of element in the list
4. Deletion of element from the list
5. Searching of element from the list 6. Exit
Enter Your choice6
Although this type of implementation is possible using arrays, it is usually not preferred to
have list implementation using arrays because of two main reasons -
Limitations
1. There is a limitation on the number of nodes in the list because of fixed size of array.
Hence sometimes memory may get wasted because of less elements in the list or there may
be large number of nodes in the list and we could not store some elements in the array.
2. Insertions and deletions of elements in the array(list) is complicated (Just refer the
functions Insert() and Delete() and feel how complicated they are!)
Hence we will go for dynamic memory allocation for implementing the list.
Key Point: The list creation using dynamic memory management is called linked list.
Ex. 1.4.1: Consider an array A[1:n]. Given a position, write an algorithm to insert an
element in the array. If the position is empty, the element is inserted easily. If the
position is already occupied the element should be inserted with the minimum number
of shifts.
(Note: The elements can shift to the left or to the right to make the minimum number of
moves)
Sol. :
Algorithm for Insertion of Element in array
Step 1: Enter the number of elements present in the array. Also enter the elements in the
array.
printf("\n How many elements are present in the array?");
scanf("%d", &n);
printf("\n Enter the elements (Type -99 for empty location): ");
for(c=0;c<n;c++)
scanf("%d",&array[c]);
Step 2: Enter the value of the element which is to be inserted in the array, say Key_Element.
Also enter the position at which this element is to be inserted.Say Key_Position.
printf("\n Enter the element to be inserted 2in the array: ");
scanf("%d", &Key_Element);
printf("\n Enter the position at which the element is to be inserted: ");
scanf("%d", &Key_Postion);
Step 3:
//If the Key_Position is empty then insert the Key_Element at that position.
if(array[Key_Postion] ==-99)
array[Key_Position] =Key_Element;
Step 4:
//Otherwise, Count the number of elements present left and right to this Key_Element. We
call it as LeftElementCount and RightElementCount.
for(i=0;i<=Key_Position-1;i++); //note the semicolon after this for loop
LeftElementCount=i;
for(j=n-1;j>=Key_Position;j-);
RightElementCount=j;
Step 5: If Left ElementCount < RightElementCount then
{
Search for empty location in this left sublist.
If empty location is present then move the elements to the left by creating space at
Key_Position then
Insert Key Element at Key_Position.
else
goto step 8
}
Step 6: If Left ElementCount> RightElementCount then
{
Search for empty location in this right sublist.
If empty location is present then move the elements to the right by creating space at
Key_Position then
Insert Key_Element at Key_Position.
else
goto step 8
}
Step 7:
//Create the space at Key_Position by shifting the last position elements to the rightmost
//empty space.
for(k=n-1;k>=Key_Position-1;k--)
{
array[k+1]=array[k];
array[Key_Position-1]=Key_Element;
}
Step 8: Display the list of elements in the array
for(c=0;c<=n;c++)
printf("%d", array[c]);
Review Question
1. What are the various operations on array ? Write a procedure to insert an element in the
middle of the array.
A linked list is a set of nodes where each node has two fields 'data' and a 'link'. Where data
field stores the actual piece of information and 'link' field is used to point to next node.
Basically link field is nothing but the address only.
Concept of Linked List
• Definition: A linked list is a set of nodes where each node has two fields 'data' and a 'link'.
Where data field stores the actual piece of information and 'link' field is used to point to next
node. Basically link field is nothing but the address only.
• Note that the link field of last node consists of 'NULL' which indicates end of linked list.
It is called singly because this list consists of only one link, to point to next node or element.
This is also called linear list because the last element points to nothing it is linear is nature.
The last field of last node is NULL which means that there is no further list. The very first
node is called head or first.
• Singly circular linked list :
In this type of linked list only one link is used to point to next element and this list is circular
means that the last node's link field points to the first or head node. That means according to
example after 40 the next number will be 10. So the list is circular in nature.
Doubly linear linked list :
This list called doubly because each node has two pointers previous and next pointers. The
previous pointer points to previous node and next pointer points to next node. Only in
case of head node the previous pointer is obviously NULL and last node's next pointer points
to NULL. This list is a linear one.
• Doubly circular linked list :
In circular doubly linked list the previous pointer of first node and the next pointer of last
node is pointed to head node. Head node is a special node which may have any dummy data
or it may have some useful information such as total number of nodes in the list which may
be used to simplify the algorithms carrying various operations on the list.
Various operations of linked list are 1. Creation of linked list, 2. Display of linked list, 3.
Insertion of any element in the linked list, 4. Deletion of any element from the linked list ,5.
Searching of desired element in the linked list.
Linked List Implementation
• Various operations of linked list are
1. Creation of linked list.
2. Display of linked list.
3. Insertion of any element in the linked list.
4. Deletion of any element from the linked list.
5. Searching of desired element in the linked list.
We will discuss each operation one by one -
1. Creation of linked list
node* create()
{
node *temp, *New, *head;
int val, flag;
char ans='y';
node *get_node();
temp = NULL;
flag =TRUE; /* flag to indicate whether a new node is created for the first time or not */
do
{
printf("\nEnter the Element :");
scanf("%d", &val);
/* allocate new node */
New =get_node();
if (New == NULL)
printf("\nMemory is not allocated");
New-> data = val;
if (flag==TRUE) /* Executed only for the first time */
{
head = New;
temp = head; /*head is a first node in the SLL*/
flag = FALSE;
}
else
{
/* temp keeps track of the most recently
created node */
temp->next = New;
temp = New;
}
printf("\n Do you Want to enter more elements? (y/n)");
ans=getche();
} while(ans=='y');
printf("\nThe Singly Linked List is created\n");
getch();
clrscr();
return head;
}
node *get_node()
{
node *temp;
temp (node *) malloc(sizeof(node));
temp->next = NULL;
return temp;
}
Creation of linked list (logic explanation part) :
Initially one variable flag is taken whose value is initialized to TRUE (i.e. 1). The purpose of
flag is for making a check on creation of first node. That means if flag is TRUE then we have
to create head node or first node of linked list. Naturally after creation of first node we will
reset the flag (i.e. assign FALSE to flag). Consider that we have entered the element value 10
initially then,
Step 1:
If (flag == TRUE)
{
Head = New
temp head;
/* We have also called this node as temp because head's address will be preserved in 'head'
and we can change 'temp' node as per requirement */
flag=FALSE;
/* After creation of first node flag is reset */
Step 3:
If head node of linked list is created we can further create a linked list by attaching the
subsequent nodes. Suppose we want to insert a node with value 20 then,
Step 4:
If user wants to enter more elements then let say for value 30 the scenario will be,
Step 5:
As now value of temp becomes NULL we will come out of while loop. As a result of such
display routine we will get,
10 20 30 40 50 → NULL
will be printed on console.
3. Insertion of any element at anywhere in the linked list
There are three possible cases when we want to insert an element in the linked list -
a) Insertion of a node as a head node.
b) Insertion of a node as a last node.
c) Insertion of a node after some node.
We will see the case a) first -
node *insert_head(node *head)
{
node *New,*temp;
New=get_node();
printf("\n Enter The element which you want to insert");
scanf("%d", &New->data);
if(head == NULL)
head=New;
else
Now we will insert a new node after some node at intermediate position
void insert_after(node *head)
{
int key;
node *New,*temp;
New= get_node();
printf("\n Enter The element which you want to insert");
scanf("%d", &New->data);
if(head == NULL)
{
head=New;
}
else
{
printf("\n Enter The element after which you want to insert the node");
scanf("%d", &key);
temp=head;
do
if(temp->data==key)
{
New->next-temp->next;
temp->next=New;
return;
}
else
temp-temp->next;
}while(temp!= NULL);
}
}
If we want to insert 31 in the linked list which is already created. We want to insert this 31
after node containing 30 then
Suppose key=30 i.e. we want a node containing value 30 then compare temp → data and key
value. If there is no match then we will mark next node as temp.
Hence print the message "The Element is present in the list".
Thus in search operation the entire list can be scanned in search of desired node. And still, if
required node is not obtained then we have to print the message.
"The Element is not present in the list"
Let us see the complete program for it -
Ex. 1.6.1: Implementation of various operations on singly linked list (SLL).
/***Program to perform various operations such as creation, insertion, deletion, search
and display on singly link lists.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct SLL
{
int data;
struct SLL *next;
}node;
node *create();
void main()
{
/* Local declarations */
int choice, val;
char ans;
node *head;
void display(node *);
node *search(node *,int);
node *insert(node *);
void dele(node **);
head=NULL;
do
{
clrscr();
printf("\nProgram to Perform Various operations on Linked List");
printf("\n1.Create");
printf("\n2.Display");
printf("\n3.Search for an item");
printf("\n4.Insert an element in a list");
printf("\n5.Delete an element from list");
printf("\n6.Quit");
printf("\nEnter Your Choice (1-6) ");
scanf("%d", &choice);
switch(choice) molenc
case 1: head = create();
break;
case 2: display(head);
break;
case 3: printf("Enter the element you want to search");
scanf("%d", &val);
search(head, val);
}
break;
case 4 head=insert(head);
break;
case 5 dele(&head);
break;
case 6 exit(0);
default:clrscr();
printf("Invalid Choice, Try again");
getch();
}
} while(choice != 6);
}
node* create()
{
node *temp, *New, *head;
int val, flag;
char ans='y';
node *get_node();
temp = NULL;
flag=TRUE; /* flag to indicate whether a new node is created for the first time or not */
do
{
printf("\nEnter the Element :");
scanf("%d", &val);
/* allocate new node */
New = get_node();
if ( New == NULL)
printf("\nMemory is not allocated");
New -> data = val;
if (flag==TRUE) /* Executed only for the first time */
{
head = New;
temp = head; /*head is a first node in the SLL*/
flag = FALSE;
}
else
{
/* temp keeps track of the most recently created node */
temp->next = New;
temp = New;
}
printf("\n Do you Want to enter more elements?(y/n)");
ans=getche();
}while(ans=='y');
printf("\nThe Singly Linked List is created\n");
getch();
clrscr();
return head;
node *get_node()
{
node *temp;
temp=(node *) malloc(sizeof(node));
temp->next = NULL;
return temp;
}
void display(node *head)
{
node *temp;
temp = head;
if (temp == NULL)
{
printf("\nThe list is empty\n");
getch();
clrscr();
return;
}
while (temp != NULL)
{
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL");
getch();
clrscr();
node *search(node *head, int key)
{
node *temp;
int found;
temp = head;
if (temp == NULL)
{
printf("The Linked List is empty\n");
getch();
clrscr();
return NULL;
}
found = FALSE;
while (temp != NULL && found == FALSE)
{
if (temp->data != key)
temp = temp->next;
else
found = TRUE;
}
if (found ==TRUE)
{
printf("\nThe Element is present in the list\n");
getch();
return temp;
}
else
{
printf("The Element is not present in the list\n");
getch();
return NULL;
}
}
/*
The insert function
Input:Address of starting node of the list
Output:inserts an element into the list
Parameter Passing Method: call by value
Called By:main
Calls search()
*/
node *insert(node *head)
{
int choice;
node *insert_head(node *);
void insert_after(node *);
void insert_last(node *);
printf("\n 1. Insert a node as a head node");
printf("\n 2. Insert a node as a last node");
printf("\n 3. Insert a node at intermediate position in the linked list"); printf("\n Enter the your
choice for insertion of node");
scanf("%d", &choice);
switch(choice)
{
case 1:head-insert_head(head);
break;
case 2:insert_last(head);
break;
case 3:insert_after(head);
New head is returned from function insert_head().
Hence we have to return the new
head from the insert function to main
break;
}
return head;
}
/* Insertion of node at first position*/
node *insert_head(node *head)
{
node *New,*temp;
New=get_node();
printf("\n Enter The element which you want to insert");
scanf("%d", &New->data);
if(head == NULL)
head=New;
else
{
temp=head;
New->next=temp;
head=New;
}
return head;
}
/*Insertion of node at last position*/
void insert_last (node *head)
{
node *New,*temp;
New=get_node();
printf("\n Enter The element which you want to insert");
scanf("%d",&New->data);
if(head== NULL)
head=New;
else
{
temp=head;
while(temp->next!= NULL)
temp-temp->next;
temp->next=New;
New->next = NULL;
}
}
/*Insertion of node at intermediate position */
void insert_after(node *head)
{
int key;
node *New,*temp;
New= get_node();
printf("\n Enter The element which you want to insert");
scanf("%d", &New->data);
if(head == NULL)
{
head=New;
}
else
{
printf("\n Enter The element after which you want to insert the node");
scanf("%d", &key);
temp=head;
do
{
if(temp->data== key)
{
New->next-temp->next;
temp->next=New;
return;
}
else
temp-temp->next;
} while(temp!= NULL);
}
}
node* get_prev(node *head, int val)
{
node *temp, *prev;
int flag;
temp = head;
if (temp==NULL)
return NULL;
flag = FALSE;
prev = NULL;
while (temp != NULL && !flag)
{
if (temp->data != val)
{
prev = temp;
temp = temp->next;
}
else
flag = TRUE;
}
if (flag )/*if flag is true*/
return prev;
else
return NULL;
/*The dele function
Input:Address of the starting node of the list
Output:deletes the desired element from the list
Parameter Passing Method: call by value
Calls search(), get_prev()
*/
void dele(node **head)
{
node *temp, *prev;
int key;
temp = *head;
if (temp == NULL)
{
printf("\nThe list is empty\n");
getch();
clrscr();
return;
}
clrscr();
printf("\nEnter the Element you want to delete: ");
scanf("%d", &key);
temp = search(*head,key);
if (temp != NULL)
{
prev = get_prev(*head,key);
if (prev != NULL)
{
prev -> next = temp->next;
free (temp);
}
else
{
*head = temp->next;
free(temp);
}
printf("\nThe Element is deleted\n");
getch();
clrscr();
}
}
Output
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 1
Enter the Element :10
Do you Want to enter more elements? (y/n)y Enter the Element :20
Do you Want to enter more elements?(y/n)y Enter the Element :30
Do you Want to enter more elements?(y/n)y Enter the Element :40
Do you Want to enter more elements?(y/n)y Enter the Element :50
Do you Want to enter more elements?(y/n)n
The Singly Linked List is created
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 2
10 - 20 -> 30 -> 40 -> 50 -> NULL
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 3
Enter the element you want to search 40
The Element is present in the list
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 4
1. Insert a node as a head node
2. Insert a node as a last node
3. Insert a node at intermediate position in the linked list
Enter the your choice for insertion of node 1
Enter The element which you want to insert 9
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 2
9-> 10-> 20 -> 30-> 40 -> 50 -> NULL
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 4
1. Insert a node as a head node
2. Insert a node as a last node
3. Insert a node at intermediate position in the linked list
Enter the your choice for insertion of node 2
Enter The element which you want to insert 60
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 2
9 - 10 - 20 -> 30-> 40 -> 50 -> 60 -> NULL
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item all beds n nouiaog
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 4
1. Insert a node as a head node
2. Insert a node as a last node
3. Insert a node at intermediate position in the linked list
Enter the your choice for insertion of node 3
Enter The element which you want to insert 31
Enter The element after which you want to insert the node 30
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 2
9 - 10 -> 20 -> 30 -> 31 -> 40 -> 50 -> 60-> NULL
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 5
Enter the Element you want to delete: 40
obor Jasis-as
The Element is present in the list
The Element is deleted
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 2
9->
10-> 20 -> 30 -> 31 -> 50 -> 60-> NULL
More Programs on Linked List
In this section we will discuss various operations that can be performed on the linked list. For
the sake of convenience we will discuss only functions performing these operations assuming
that the list is already created. The create() and display() functions will be common to all
these operations.
Ex. 1.6.2 Counting the nodes of linked list.
Sol;
void count()
{
node *temp;
int c=0;
temp=head;
if(temp== NULL)
{
printf("\n The list is empty");
return;
}
while(temp!= NULL)/*visiting each node*/
{
c=c+1;/*c is for counting the node*/
temp-temp->next;
}
printf("\nThe Total number of nodes are: %d",c);
getch();
}
Ex. 1.6.3 Concatenation of two linked list.
Sol. :
void concat(node *head1,node *head2)
{
node *temp1,*temp2;
temp1=head1;
temp2=head2;
while(temp1->next!= NULL)
temp1=temp1->next;/*searching end of first list*/
temp1->next=temp2;/* attaching head of the second list*/
printf("\n The concatenated list is ...\n");
temp1=head1;
while(temp1!= NULL)
{ /*printing the concatenated list*/
}
printf("%d",temp1->Data);
temp1=temp1->next;
}
}
Ex. 1.6.4 Algorithm to copy one singly list to another.
Sol.:
void copy(node *head1,node *head2)
{
node *temp1, *temp2;
temp1=head1;/*first non empty linked list*/
head2=(node *)malloc(sizeof(node));
temp2-head2;/* second empty linked list*/
while(temp1!= NULL)/*while not end of first linked list*/
{
temp2->data=temp1->data;/*copy the content to other node*/
temp2->next=(node *)malloc(sizeof(node));
temp2=temp2->next;/* moving one node ahead */
temp1=temp1->next;
}
temp2=NULL;/*set the next pointer of last node of second list to NULL*/
printf("\n The list is copied \n");
while(head2->next!= NULL)
{
/*printing the second list i.e. copied list*/
printf("%d",head2->data); head2-head2->next;
}
}
Ex. 1.6.5 Recursive routine to erase a linked list (delete all node from the linked list).
Sol. :
struct node *list_free(struct node *temp)
{
if(temp->next!= NULL)
{
temp1=temp->next;/*temp1 is declared globally*/
temp->next=NULL;
free(temp);
list_free(temp1);/*recursive call*/
}
temp=NULL;
return temp;
}
Ex. 1.6.6 Write a routine to merge two sorted linked lists.
Sol.
Consider two linked lists
node *merge(node *temp1,node *temp2)
{
node *prev_node1, *next_node2, *head;
if(temp1== NULL)
{
temp1=temp2;
head=temp2;
}
if(temp1->data<temp2->data)
head=temp1;
else
head=temp2;
while(temp1!= NULL && temp2!= NULL)
{
/*while data of 1st list is smaller then traverse*/
while((temp1->data<temp2->data) && (temp1!= NULL))
{
prev_node1=temp1; /* store prev node of Sl11 */
temp1=temp1->next;
}
if(temp1== NULL)
break;
/*when temp1's data>temp1 it will come out
of while loop so adjust links with temp1's prev node*/
prev_node1->next=temp2;
next_node2=temp2->next; /*store next node of Sl12*/
temp2->next=temp1;
temp1=temp2;
temp2=next_node2;
}
if(temp1==NULL&&temp2!=NULL) /*attach rem nodes of S112*/
{
while(temp2!= NULL)
{
prev_node1->next=temp2;
prev_node1=temp2;
temp2=temp2->next;
}
}
return head;
}
Ex. 1.6.7
Returning the position of an element X in a list L.
Sol.
The routine is as given below -
Return_position(node *head,int key)
{
/* head represents the starting node of the List*/
/* key represents the element X in the list*/
int count=0;
node *temp;
temp=head;
while(temp->data!=key)&&(temp!= NULL)
{
temp-temp->next;
count=count+1;
}
if(temp->data==key)
return count;
else if(temp== NULL)
return -1; /* -1 indicates that the element X is not present in the list*/
Ex. 1.6.8 Write a C function to display the sum of all the elements in a singly linked list.
Sol. :
void sum(node *head)
{
node *temp;
int s=0;
temp=head;
while(temp!= NULL)
{
s=s+temp->data;
temp-temp->next;
}
printf("%d",s);
}
Ex. 1.6.9 Assume a singly linked list where each node contains student details like name,
rollno and percentage of marks. Write a "C" function COUNTO to traverse the linked
list and count how many students have obtained more than 60 %.
Sol. The data structure can be
struct student
{
char *name;
};
int roll;
float marks;
struct student *next;
};
The COUNT function can be written as
void COUNT(struct student *temp)
{
int count=0;
while(temp!= NULL)
{
if(temp->marks>60)
count++;
temp-temp->next;
}
printf("\n\n %d students have obtained more than 60 Percentage", count);
}
Ex. 1.6.10: Write a C program to create a singly linked list and split it at the middle.
And make the second half as the first and vice versa, display the final list.
Sol. :
typedef struct node
{
int data;
struct node *next;
}node;
void main().
{
node*head=NULL,*p,*q;
int n,i,x;
printf("\nEnter number of nodes:");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\nEnter element:");
scanf("%d",&x);
p=(node*)malloc(size of(node));
p->data=x;
p-next=NULL;
if(head= NULL)
head=q=p;
else
{
q->next=p;
q=p;
}
}
p=q=head;
while(q->next!= NULL)
{
p=p->next;
q=q->next;
if(q->next!= NULL)
q=q->next;
}
q-next-head;
head-p->next;
p->next=NULL;
for(p=head;p!= NULL;p=p->next)
printf("\n%d",p->data);
}
Ex. 1.6.11: Write a function that removes all duplicate elements from a linear singly
linked list.
Sol. :
void dupdelete(node*head)
{
node *p, *q,*I;
p=head;
q=p->next;
while(q!= NULL)
{
if(p->data!=q->data)
{
p-p->next;
q-q->next;
}
else
if(p->data==q->data)
{
p->next=q->next;
r=q;
q=q->next;
free(r);
}
return(head);
}
}
Ex. 1.6.12: Suppose a linked list consists of numerical values. Write a function for
finding the maximum element of the list and the product of all the numbers in the list.
Sol. i) To find the maximum element in the linked list :
void maxElement(node *root)
{
node *temp;
int Maxval;
temp=root;
Maxval=temp->data;
while(temp!= NULL)
{
if(temp->data>Maxval)
{
Maxval-temp->data;
}
temp-temp->next;
}
printf("\n Maximum Value is: %d", Maxval);
}
ii) To find the product of all numbers in the linked list :
void Product(node *root)
{
node *temp;
int p=1;
temp=root;
while(temp!= NULL)
{
p=p*temp->data;
temp-temp->next;
}
printf("\n Product of all the elements: %d",p);
}
Review Questions
1. Write C code for singly liked list with insert, delete, display operations using
structure pointer.
2. What are the ways to insert a note in linked list? Write an algorithm for inserting a
node before a given node in a linked list.
3. Explain the insertion operation linked list. How nodes are inserted after a specified
node ?
Using array, any element can be accessed easily.It takes constant time. In linked list, we can
access elements in sequence. So it is very difficult and time consuming to access a element
randomly.
Difference between Array and Linked Listed:
The comparison between linked list and arrays is as shown below -
Ex. 1.7.1 Compare linked list with arrays with reference to the following aspects:
i) Accessing any element randomly
ii) Insertion and deletion of an element
iii) Utilization of computer memory.
Sol. i) Accessing any element randomly: Using array, any element can be accessed easily.
a) It takes constant time.
b) In linked list, we can access elements in sequence. So it is very difficult and time
consuming to access a element randomly.
ii) Insertion and deletion of an element :
a) Insertion and deletion of elements is time consuming.
b) In linked list, we can insert and delete elements easily and it is less time consuming.
iii) Utilization of computer memory:
a) Array requires contiguous memory. First we have to declare array and compiler allocates
memory at declaration.
b) If we utilize less memory than allocated, then unutilized memory is unnecessarily reserved
for array. It can't be used by other programs.
c) If we want to add more elements than the actual size of array, it is not possible.
d) In linked list, memory is utilized efficiently. Memory is not pre-allocated like static data
structure. Memory is allocated as per the need. Memory is deallocated when it is no longer
needed.
The Circular Linked List (CLL) is similar to singly linked list except that the last node's next
pointer points to first node.
Circularly Linked List
Definition: The Circular Linked List (CLL) is similar to singly linked list except that the last
node's next pointer points to first node.
The circular linked list is as shown below
temp=head;
while (temp->next!= head)/*finding the last node*/
}
temp-temp->next; /*temp is a last node */
temp->next=New;
New->next = head; /*each time making the list circular*/
}
printf("\n Do you want to enter more nodes?");
ans=getch();
}while(ans=='y' || ans =='=='Y');
return head;
}
struct node *get_node()
{
struct node *New;
New = (node *) malloc(sizeof(struct node));
New->next = NULL;
return(New);/*created node is returned to calling function*/
}
void Display(struct node *head)
{
struct node *temp;
temp = head;
if(temp==NULL)
printf("\n Sorry,The List Is Empty\n");
else
{
do
{
printf("%d\t",temp->data);
temp = temp->next;
} while(temp != head);/*Circular linked list*/
}
getch();
}
struct node *Insert(node *head)
{
int choice;
struct node *insert_head(node *);
void insert_after(struct node *);
void insert_last(struct node *);
printf("\n 1. Insert a node as a head node");
printf("\n 2. Insert a node as a last node");
printf("\n 3. Insert a node at intermediate position in the linked list");
printf("\n Enter your choice for insertion of node");
scanf("%d", &choice);
switch(choice)
{
case 1: head-insert_head(head);
break;
case 2: insert_last(head);
break;
case 3: insert_after(head);
break;
}
return head;
}
struct node *insert_head(struct node *head)
{
struct node *get_node();
struct node *New,*temp;
New=get_node();
printf("\n Enter The element which you want to insert ");
scanf("%d", &New->data);
if(head == NULL)
head=New;
else
{
temp=head;
while(temp->next!=head)
temp-temp->next;
temp->next=New;
New->next-head;
head=New;
printf("\n The node is inserted!");
}
return head;
/*Insertion of node at last position*/
void insert_last(struct node *head)
{
struct node *New,*temp;
New=get_node();
printf("\n Enter The element which you want to insert ");
scanf("%d", &New->data);
if(head= NULL)
else
{
head=New;
temp=head;
while(temp->next!=head)
temp-temp->next;
temp->next=New;
New->next = head;
printf("\n The node is inserted!");
}
}
void insert_after(struct node *head)
{
int key;
struct node *New,*temp;
New= get_node();
printf("\n Enter The element which you want to insert ");
scanf("%d", &New->data);
if(head == NULL)
{
head=New;
}
else
{
printf("\n Enter The element after which you want to insert the node");
scanf("%d", &key);
temp=head;
do
{
if(temp->data==key)
{
New->next-temp->next;
temp->next=New;
printf("\n The node is inserted");
return;
}
else
temp-temp->next;
} while(temp!=head);
}
}
struct node *Search(node *head,int num)
{
struct node *temp;
temp=head;
while(temp->next!=head)
{
if(temp->data == num)
return temp;/*if node is found*/
else
temp-temp->next;
}
return NULL;
}
struct node *Delete(struct node *head)
{
int key;
struct node *temp, *temp1;
printf("\n Enter the element which is to be deleted");
scanf("%d",&key);
temp=head;
if(temp->data==key)/*If header node is to be deleted*/
{
temp1=temp->next;
if(temp1==temp)
/*if single node is present in circular linked list and we want to delete it*/
{
temp=NULL;
head=temp;
printf("\n The node is deleted");
}
else /*otherwise*/
{
while(temp->next!=head)
temp-temp->next;/*searching for the last node*/
temp->next=temp1;
head-temp1;/*new head*/
printf("\n The node is deleted");
}
}
else
{
while(temp->next!=head) /* if intermediate node is to be deleted*/
{
if((temp->next)->data==key)
{
temp1=temp->next;
temp->next-temp1->next;
temp1->next = NULL;
free(temp1);
printf("\n The node is deleted");
}
else
temp-temp->next;
}
}
return head;
}
Output
Program For Circular Linked List
1. Insertion of any node
2. Display of Circular List
3. Insertion of a node in Circular List
4. Deletion of any node
5. Searching a Particular Element in The List
6. Exit
Enter Your Choice 1
10
Enter The Element
Do you want to enter more nodes?mo nisi d'oe
Enter The Element
20
Do you want to enter more nodes?
Enter The Element
30
Do you want to enter more nodes? Enter The Element
40
Do you want to enter more nodes?
Do you want to go to Main Menu?
Program For Circular Linked List
1. Insertion of any node
2. Display of Circular List
3. Insertion of a node in Circular List
4. Deletion of any node
5. Searching a Particular Element in The List
6. Exit
Enter Your Choice 2
10 20 30 40
Do you want to go to Main Menu?
Program For Circular Linked List
1.Insertion of any node
2. Display of Circular List
3. Insertion of a node in Circular List
4. Deletion of any node
5. Searching a Particular Element in The List
6.Exit
Enter Your Choice 3
1. Insert a node as a head node
2. Insert a node as a last node
3. Insert a node at intermediate position in the linked list
Enter your choice for insertion of node 3
Enter The element which you want to insert 33
Enter The element after which you want to insert
the node 30
The node is inserted
Do you want to go to Main Menu?
Program For Circular Linked List
1. Insertion of any node
2. Display of Circular List
3. Insertion of a node in Circular List
4. Deletion of any node
5. Searching a Particular Element in The List
6. Exit
Enter Your Choice 2
10 20 30 33 40
Program For Circular Linked List
1. Insertion of any node
2. Display of Circular List
3. Insertion of a node in Circular List
4. Deletion of any node
5. Searching a Particular Element in The List
6. Exit
Enter Your Choice 4
Enter the element which is to be deleted 20
The node is deleted
Do you want to go to Main Menu?
Program For Circular Linked List
1. Insertion of any node
2. Display of Circular List
3. Insertion of a node in Circular List
4. Deletion of any node
5. Searching a Particular Element in The List of
6. Exit
Enter Your Choice 2
10 30 33 40
Do you want to go to Main Menu?
Program For Circular Linked List
1. Insertion of any node
2. Display of Circular List
3. Insertion of a node in Circular List
4. Deletion of any node
5. Searching a Particular Element in The List
6. Exit
Enter Your Choice 5
Enter The Element Which Is To Be Searched 30
The node is present
Do you want to go to Main Menu?
Program For Circular Linked List
1. Insertion of any node
2. Display of Circular List
3. Insertion of a node in Circular List
4. Deletion of any node
5. Searching a Particular Element in The List
6. Exit
Enter Your Choice 5
Enter The Element Which Is To Be Searched 101
The node is not present
Do you want to go to Main Menu?
Program For Circular Linked List
1. Insertion of any node
2. Display of Circular List
3. Insertion of a node in Circular List
4. Deletion of any node
5. Searching a Particular Element in The List
6. Exit
Enter Your Choice 6
Advantages of Circular Linked List over Singly Linked List
In circular linked list the next pointer of last node points to the head node. Hence we can
move from last node to the head node of the list very efficiently. Hence accessing of any node
is much faster than singly linked list.
Applications of circular list :
1) The circular list is used to create the linked lists in which the last node points to the first
node.
2) In round robin method the circular linked list is used.
3) The circular linked list is used in solving Josephus problem. 4) For representing the
polynomial the circular linked list.
Review Question
1. Write a procedure to deleting the last node from a circular linked list.
The doubly linked list has two link fields. One link field is previous pointer and the other link
field is that next pointer.
Doubly Linked List
• Definition: The doubly linked list has two link fields. One link field is previous pointer and
the other link field is that next pointer.
• The typical structure of each node in doubly linked list is like this.
• C Structure
'C' structure of doubly linked list is as follows -
typedef struct node
{
int data;
struct node *prev;
struct node *next;
}dnode;
• Representation
The linked representation of a doubly linked list is
Thus the doubly linked list can traverse in both the directions, forward as well as backwards.
Now, there may be one question in your mind that bon how do the empty doubly circular
linked lists look ? he? Here is the representation.
That means the prev and next pointers are pointing to the self node.
Ex. 1.9.1 Implementation of doubly linked list.
/*****************************************************
Program to perform various operations
such as creation, insertion, deletion, search and display
on doubly link lists.
******************************************************
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct DLL
{
int data;
struct DLL *next;
struct DLL *prev;
}node;
node *create();
/*
The main function
*/
void main()
{
/* Local declarations */
int choice, val;
char ans;
node *head;
void display(node *);
node *search(node *,int);
node *insert(node *);
void dele(node **);
head=NULL;
do
{
clrscr();
printf("\nProgram to Perform Various operations on Linked List");
printf("\n1.Create");
printf("\n2.Display");
printf("\n3.Search for an item");
printf("\n4.Insert an element in a list"); printf("\n5.Delete an element from list");
printf("\n6.Quit");
printf("\nEnter Your Choice (1-6) ");
scanf("%d", &choice);
switch(choice)
{
case 1:head = create();
break;
case 2:display(head);
break;
case 3:printf("Enter the element you want to search");
scanf("%d", &val);
search(head, val);
break;
case 4:head insert(head);
break;
case 5:dele(&head);
break;
case 6:exit(0);
default:clrscr();
printf("Invalid Choice, Try again");
getch();
}
} while(choice != 6);
*/
The create function
*/
node* create()
{
node *temp, *New, *head;
int val, flag;
char ans='y';
node *get_node();
temp = NULL;
flag = TRUE; /* flag to indicate whether a new node
is created for the first time or not */
do
{
printf("\nEnter the Element :");
scanf("%d", &val);
/* allocate new node */
New =get_node();
if (New == NULL)
printf("\nMemory is not allocated");
New-> data = val;
if (flag==TRUE) /* Executed only for the first time */
{
head=New;
temp=head; /*head is a first node in the DLL*/
flag = FALSE;
}
else
{
/* temp keeps track of the most recently created node */
temp->next = New;
New->prev=temp;
temp = New;
}
printf("\n Do you Want to enter more elements?(y/n)");
ans=getche();
} while(ans=='y');
printf("\nThe Doubly Linked List is created\n");
getch();
clrscr();
return head;
}
node *get_node()
{
node *temp;
temp=( node *)malloc(sizeof(node));
temp->next=NULL;
temp->prev=NULL;
return temp;
}
/*
The display function
Input:Address of the first node of the list
Output:Displays the Linked List
Parameter Passing Method: call by value
Called by main
*/
void display(node *head)
{
node *temp;
temp = head;
if (temp == NULL)
{
printf("\nThe list is empty\n");
getch();
clrscr();
return;
}
printf("\n List in Forward direction is ...\n");
while (temp != NULL)
{
printf("%d -> ", temp->data ); herrefe
temp = temp->next;
}
printf("NULL");
temp=head;
while(temp->next!= NULL)
temp-temp->next;//reaching at the last node
printf("\n List in Reverse direction is ...\n");
while (temp != NULL)
{
printf("%d-> ", temp->data);
temp = temp -> prev;
}
printf("NULL");
getch();
clrscr();
}
/*
The search function
*/
node *search(node *head, int key)
{
node *temp;
int found;
temp=head;
if (temp = = NULL)
{
printf("The Linked List is empty\n");
getch();
clrscr();
return NULL;
}
found=FALSE;
while (temp != NULL && found == FALSE)
{
if (temp->data != key)
temp = temp ->next;
else
found = TRUE;
}
if (found ==TRUE)
{
printf("\nThe Element is present in the list\n");
getch();
return temp;
}
else
{
printf("The Element is not present in the list\n");b)
getch();
return NULL;
}
}
/*
The insert function
Input Address of starting node of the list
Output:inserts an element into the list
*/
node *insert(node *head)
{
int choice;
node *insert_head(node *);
void insert_after(node *);
void insert_last(node *);
printf("\n 1. Insert a node as a head node");
printf("\n 2. Insert a node as a last node");
printf("\n 3. Insert a node at intermediate position in the linked list");
printf("\n Enter the your choice for insertion of node");
scanf("%d", &choice);
switch(choice)
{
case 1:head-insert_head (head);
break;
case 2:insert_last(head);
break;
case 3:insert_after(head);
break;
}
return head;
}
/* Insertion of node at first position*/
node *insert_head(node *head)
{
node *New,*temp;
New=get_node();
printf("\n Enter The element which you want to insert");
scanf("%d", &New->data);
if(head == NULL)
head=New;
else
{
temp=head;
New->next=temp;
temp->prev=New;
head=New;
}
return head;
}
/*Insertion of node at last position*/
void insert_last(node *head)
{
node *New,*temp;
New=get_node();
printf("\n Enter The element which you want to insert");
scanf("%d", &New->data);
if(head == NULL)
head=New;
else
{
temp=head;
while(temp->next!= NULL)
temp-temp->next;
temp->next=New;
New->prev=temp;
New->next=NULL;
}
}
/*Insertion of node at intermediate position*/
void insert_after(node *head)
{
int key;
node *New,*temp;
New = get_node();
printf("\n Enter The element which you want to insert");
scanf("%d", &New->data);
if(head = NULL)
{
head=New;
}
else
{
printf("\n Enter The element after which you want to insert the node");
scanf("%d", &key);
temp=head;
do
{
if(temp->data==key)
{
New->next-temp->next;
(temp->next)->prev=New;
temp->next=New;
New->prev=temp;
return;
}
else
temp-temp->next;
}while(temp!= NULL);
}
}
/*
The dele function
Input:Address of the starting node of the list Output:deletes the desired element from the list
Parameter Passing Method : call by value
*/
void dele(node **head)
{
node *temp, *prev_node;
int key;
temp = *head;
if (temp == NULL)
{
printf("\nThe list is empty\n");
getch();
clrscr();
return;
}
clrscr();
printf("\nEnter the Element you want to delete: ");
scanf("%d", &key);
temp = search(*head,key);
if (temp!= NULL)
{
prev_node = temp->prev;
if (prev_node != NULL)
{
prev_node->next = temp->next;
(temp->next)->prev = prev_node;
free (temp);
}
else
{
*head = temp->next;
(*head)->prev=NULL;
free(temp);
}
printf("\nThe Element is deleted\n");
getch();
clrscr();
}
}
Output
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 1
Enter the Element :10
Do you Want to enter more elements?(y/n)y
Enter the Element :20
Do you Want to enter more elements?(y/n)y
Enter the Element :30
Do you Want to enter more elements?(y/n)y
Enter the Element :40
Do you Want to enter more elements? (y/n)n
The Doubly Linked List is created
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list 6. Quit
Enter Your Choice (1-6) 2
List in Forward direction is ...
10-> 20 -> 30-> 40-> NULL
List in Reverse direction is ...
40-> 30-> 20 -> 10-> NULL
Program to Perform Various operations on Linked List or more of ritsmoll
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 3
Enter the element you want to search 30
The Element is present in the list
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 4
1. Insert a node as a head node
2. Insert a node as a last node
3. Insert a node at intermediate position in the linked list
Enter the your choice for insertion of node 1
Enter The element which you want to insert 9
Program to Perform Various operations on Linked List
1. Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 2
List in Forward direction is
9->10-> 20 -> 30-> 40 -> NULL
List in Reverse direction is ...
40 -> 30-> 20 -> 10 -> 9-> NULL
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 2
Enter the Element you want to delete: 20
The Element is present in the list
The Element is deleted
Program to Perform Various operations on Linked List
1.Create
2.Display
3.Search for an item
4.Insert an element in a list
5.Delete an element from list
6. Quit
Enter Your Choice (1-6) 2
List in Forward direction is ...
9 - 10 -> 30-> 40 -> NULL
List in Reverse direction is ...
40 -> 30 -> 10 -> 9-> NULL
Logic explanation of DLL program
1. Creation of doubly linked list
Step 1: Initially one variable flag is taken whose value is initialized to TRUE. The purpose of
this flag is for making a check on creation of first node. After creating first node reset flag
(i.e. assign FALSE to flag)
Step 2: If head node is created, we can further create a linked list by attaching the subsequent
nodes. Suppose, we want to insert a node with value 20 then
Case 2: Insertion of a node at the end suppose we want to insert a node with value 40 then,
first move temp pointer to the last node
4. Deletion of node
Suppose we want to delete a node with a value 20 then, first search this node, call it as temp.
Singly and Doubly Linked List Comparison
Review Questions
1. What is meant by doubly linked list? Write the functions to perform the following
operations in a doubly linked list. i) Insert after a specified node ii) Delete the node at a
given position iii) Display-from the beginning to end.
2. Illustrate the algorithms to implement the doubly linked list and perform all the
operations on the created list.
The linked list is a data structure which makes use of dynamic memory. Hence it is possible
to handle the list of any desired length using the linked list.
Applications of Lists
The linked list is a data structure which makes use of dynamic memory. Hence it is possible
to handle the list of any desired length using the linked list. Various applications of linked list
are -
1. The linked list is used for performing polynomial operations such as addition,
multiplication evaluation and so on.
2.The linked list is used for handling the set operations.
3. The stack data structure can be implemented using linked list.
4. The queue data structure can be implemented using linked list.
Review Question
1. What are the applications of linked list in dynamic storage management?
A polynomial has the main fields as coefficient, exponent.In linked list it will have one more
field called 'link' field to point to next term in the polynomial.
Polynomial ADT
• A polynomial has the main fields as coefficient, exponent.
• In linked list it will have one more field called 'link' field to point to next term in the
polynomial.
• If there are n terms in the polynomial then n such nodes has to be created.
• The typical node will look like this.
• In each node, the exponent field will store exponent corresponding to that term, the
coefficient field will store coefficient corresponding to that term and the link field will point
to next term in the polynomial. Again for simplifying the algorithms such as addition of two
polynomials we will assume that the polynomial terms are stored in descending order of
exponents.
• The node structure for a singly linked list for representing a term of polynomial can be
defined as follows:
typedef struct Pnode
{
float coef;
int exp;
struct node *next;
} p;
Advantages of linked representation over arrays :
1. Only one pointer will be needed to point to first term of the polynomial.
2. No prior estimation on number of terms in the polynomial is required. This results in
flexible and more space efficient representation.
3. The insertion and deletion operations can be carried out very easily without movement of
data.
Disadvantage of linked representation over arrays :
We can not access any term randomly or directly we have to go from start node always.
Addition of Two Polynomials using Singly Linked List
Logic for polynomial addition by linked list :
Step 1: First of all we create two linked polynomials.
For e.g.:
P1 = 3x3 +2x2 + 1x
P2 = 5x5 +3x2 +7
Each node in the polynomial will look like this.
Step 2: For addition of two polynomials if exponents of both the polynomials are same then
we add the coefficients. For storing the result we will create the third linked list say p3. The
processing will be as follows:
Step 3:
Step 4:
Step 5:
Step 6:
Finally
Procedures for addition and multiplication - Refer : Addition of Two Polynomials using
Singly Linked List
Review Questions
1. Write a function to add two Polynomials using linked list.
2. Write a C program to add two polynomials using linked list
A multi-list is a data structure in which there are multiple links from a node.In a general
multi-list, each node can have any number of pointers to other nodes and there may or may
not be inverses for each pointer.
Multilists
• Basic concept: A multi-list is a data structure in which there are multiple links from a node.
• In a general multi-list, each node can have any number of pointers to other nodes and there
may or may not be inverses for each pointer.
• Multi-lists is a technique in which multiple lists are embedded into a single structure. In
multi-list the pointers are used to make multiple link routes through data.
1. Example 1: Multiple orders of one set of elements
Suppose, we have the names and ages of the students as (Monika, 25), (Varsha, 23), (Supriya,
27), (Swati, 24). We can order the above elements alphabetically (By name) or we can order
them by numbers (By age). Here the solid link is for ascending order of names and the dotted
link is for ascending order of age.
2. Sparse matrix representation using multi-lists
• Defintion: A sparse matrix is a kind of matrix which has a very few non zero elements, as
compared to the size m x n of the matrix.
• For example - If the matrix is of size 100 x 100 and only 10 elements are non zero. The
concept of sparse matrix has came forward in computer science to investigate such a
representation which will store only non-zero elements of the matrix and still carry out the
operations quite efficiently.
Representations of sparse matrices :
• The representation of sparse matrix will be a triplet only. In the sense that basically the
sparse matrix means very few non-zero elements having in it. Rest of the spaces are having
the values zero which are basically useless values or simply empty values. So in this efficient
representation we will consider all the non-zero values along with their positions.
• The 0th row will store total rows of the matrix, total columns of the matrix and total
• For example - Suppose a matrix is 6 × 7 and number of non zero terms are say 8. In our
sparse matrix representation the matrix will be stored as
In above representation, the total number of rows and columns of the matrix (6 × 7) are given
in 0th row. Also total number of non-zero elements are given in 0th row of value column i.e.
8.
Here the above array is say named "Sparse". Then
Sparse [0][0] = 6
Sparse [0][1] = 7
Sparse [0][2] = 8
Sparse [1][0] = 0
Sparse [1][1]=6
Sparse [1][2] =-10 and so on.
While representing the sparse matrix using linked list, we will make use of two types of
nodes, header node and element node.
Ex. 1.12.1 For the given sparse matrix, write the diagrammatic linked list
representation.
Two Marks Questions with Answers
Q.1 Explain the term data structure.
Ans. : The data structure can be defined as the collection of elements and all the possible
operations which are required for those set of elements. Formally data structure can be
defined as a data structure is a set of domains D, a set of functions F and a set of axioms A.
This triple (D, F, A) denotes the data structure d.
Q.2 What do you mean by non linear data structure? Give examples.
Ans. : The non linear data structure is the kind of data structure in which the data may be
arranged in hierarchical fashion. For example - Trees and graphs.
Q.3 What do you mean by linear data structure? Give example.
Ans. : The linear data structure is a kind of data structure in which the data is linearly
arranged. For example - Stacks, queues, linked list.
Q.4 Enlist the various operations that can be performed on data structure.
Ans. : Various operations that can be performed on the data structure are -
1. Create
2. Insertion of element
3. Deletion of element
4. Searching for the desired element
5. Sorting the elements in the data structure
6. Reversing the list of elements.
Q.5 What is abstract data type? What are all not concerned in an ADT ?
Ans; The abstract data type is a triple of D i.e. set of axioms, F-set of functions and A-
Axioms in which only what is to be done is mentioned but how is to be done is not
mentioned. Thus ADT is not concerned with implementation details.
Q.6 List out the areas in which data structures are applied extensively.
Ans. Following are the areas in which the data structures are applied extensively.
1. Operating system - The data structures like priority queues are used for scheduling the
jobs in the operating system.
2. Compiler design - The tree data structure is used in parsing the source program. Stack
data structure is used in handling the recursive calls.
3. Database management system - The file data structure is used in database management
systems. Sorting and searching techniques can be applied on these data in the file.
4. Numerical analysis package - The array is used to perform the numerical analysis on the
given set of data.
5. Graphics -The array and linked list are useful in graphics applications.
6. Artificial intelligence -The graph and trees are used for the applications like building
expression trees, game playing.
7. Networking - The graph is used for finding the shortest path length between any two
computers that are connected in a LAN.
8. Simulation - The queue is used for simulation and modeling.
Q.7 What is a linked list ?
Ans. : A linked list is a set of nodes where each node has two fields 'data' and 'link'. The data
field is used to store actual piece of information and link field is used to store address of next
node.make sure
Q.8 What are the pitfalls encountered in singly linked list ?
Ans. : Following are the pitfalls encountered in singly linked list :
1. The singly linked list has only forward pointer and no backward link is provided. Hence
the traversing of the list is possible only in one direction. Backward traversing is not possible.
2. Insertion and deletion operations are less efficient because for inserting the element at
desired position the list needs to be traversed. Similarly, traversing of the list is required for
locating the element which needs to be deleted.
Q.9 Define doubly linked list.
Ans; Doubly linked list is a kind of linked list in which each node has two link fields. One
link field stores the address of previous node and the other link field stores the address of
next node.
Using doubly linked list traversing the linked list in forward and backward direction becomes
efficient.
Q.10 Write down the steps to modify a node in linked lists.
Ans. :
1. Enter the position of the node which is to be modified.
2. Enter the new value for the node to be modified.
3. Search the corresponding node in the linked list.
4. Replace the original value of that node by a new value.
5. Display the message as "The node is modified".
Q.11 Differentiate between arrays and lists.
Ans; In arrays any element can be accessed randomly with the help of index of array,
whereas in lists any element can be accessed by sequential access only.
Insertions and deletions of data is difficult in arrays on the other hand insertion and deletion
of data is easy in lists.
Q.12 State the properties of LIST abstract data type with suitable example.
Ans. : Various properties of LIST abstract data type are -
1. It is linear data structure in which the elements are arranged adjacent to each other.
2. It allows to store single variable polynomial.
3. If the LIST is implemented using dynamic memory then it is called linked list. Example of
LIST are - Stacks, Queues, Linked List.
Q.13 State the advantages of circular lists over doubly linked list.
Ans. : In circular list the next pointer of last node points to head node, whereas in doubly
linked list each node has two pointers: One previous pointer and another is next pointer. The
main advantage of circular list over doubly linked list is that with the help of single pointer
field we can access head node quickly. Hence some amount of memory get saved because in
circular list only one pointer field is reserved.
Q.14 What are the advantages of doubly linked list over singly linked list ?
Ans. : The doubly linked list has two pointer fields. One field is previous link field and
another is next link field.
Because of these two pointer fields we can access any node efficiently whereas in singly
linked list only one pointer field is there which stores forward pointer, which makes
accessing of any node difficult one.
Q.15 Why is linked list used for polynomial arithmetic ?
Ans. : Following are the reasons for which linked list is used for polynomial arithmetic -
i) We can have separate coefficient and exponent fields for representing each term of
polynomial. Hence there is no limit for exponent. We can have any number as an exponent.
ii) The arithmetic operation on any polynomial of arbitrary length is possible using linked
list.
Q.16 What is the advantage of linked list over arrays ?
Ans. : The linked list makes use of the dynamic memory allocation. Hence the user can
allocate or de allocate the memory as per his requirements. On the other hand, the array
makes use of the static memory location. Hence there are chances of wastage of the memory
or shortage of memory for allocation.
Q.17 What is circular linked list ?
Ans. The circular linked list is a kind of linked list in which the last node is connected to the
first node or head node of the linked list.
Refer section 1.8.
Q.18 What is the basic purpose of header of the linked list?
The header node is the very first node of the linked list. Sometimes a dummy value such as -
999 is stored in the data field of header node. Refer Fig. 1.13.1.
This node is useful for getting the starting address of the linked list. As there is only a
forward link present in the linked list, for accessing the entire linked list it is necessary to
obtain the starting address of the linked list.
Q.19 What is advantage of an ADT ?
Ans. : The advantages of ADT are -
1. Change: The implementation of the ADT can be changed without making changes in the
client program that uses the ADT.
2. Understandability: ADT specifies what is to be done and does not specify the
implementation details. Hence code becomes easy to understand due to ADT.
3. Reusability: The ADT can be reused by some program in future.
4. Flexibility: Different implementations are possible for the same ADT.
Q.20 Should arrays of linked lists be used for the following type of applications. Justify
your answer.
a) Many search operations in sorted list.
b) Many search operations in unsorted list.
Ans. : a) If the list is sorted then using linked list the desired element can be searched, simply
by moving forward using 'next' pointer.
b) If a list is not sorted then using arrays the desired element can be searched. The arrays
facilitates the access to random element.
Q.21 What are abstract data type ?
OR Define ADT
Ans. : Refer Q.5.
Q.22 What is static linked list ? State any two applications of it.
Ans. : The linked list structure which can be represented using arrays is called static linked
list.
1. It is easy to implement, hence for creation of small databases, it is useful.
2. The searching of any record is efficient, hence the applications in which the record need to
be searched quickly, the static linked lists are used.
Q.23 Write syntax of calloc() and relloc() and mention its applications in the linked list.
Ans. : calloc() is for allocating the required amount of memory. The syntax is void
*calloc(size_t nitems, size_t size)
This function returns the pointer to the allocated memory. The calloc function is just similar
to malloc but it initializes the allocated memory to zero and malloc does not.
The realloc() function modifies allocated memory size by malloc() and calloc() functions to
new size. The syntax is
void *realloc (void *ptr, size_t size)
If insufficient memory exists then to expand the memory block, realloc() is used..
Q.24 State the advantage of ADT.
Ans. : Abstract Data Type (ADT) specifies only what kind of operations are to be done on
data structure. It does not specify how to do those operations.
• Thus implementation details can be hidden from end user, and only important properties are
represented to the user.
• ADT represents only abstract view hence it is easy for the user to understand data structure
in simplistic manner.
Q.25 What are the disadvantages of linked list over arrays.
Ans. :
1) In linked list, we can access elements in sequence. So it is very difficult and time
consuming to access element randomly.
2) Some amount of memory gets wasted in storing the next node's address in each nodes.