0% found this document useful (0 votes)
28 views37 pages

Unit 5 Lists

This document provides an overview of lists as a sequential data structure, detailing their implementation through static (array lists) and dynamic (linked lists) data structures. It discusses the basic operations of lists, their advantages and disadvantages, and compares array and linked list implementations. Additionally, it covers various types of linked lists, including singly, doubly, and circular linked lists, along with their respective operations and a sample implementation in C programming.

Uploaded by

rabinbruhh777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views37 pages

Unit 5 Lists

This document provides an overview of lists as a sequential data structure, detailing their implementation through static (array lists) and dynamic (linked lists) data structures. It discusses the basic operations of lists, their advantages and disadvantages, and compares array and linked list implementations. Additionally, it covers various types of linked lists, including singly, doubly, and circular linked lists, along with their respective operations and a sample implementation in C programming.

Uploaded by

rabinbruhh777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit – 5: Lists

Introduction:
A list is a sequential data structure. It differs from the stack and queue data, structures in that
additions and removals can be made at any position in the list.
A list is an ordered data structure with elements separated by a comma and enclosed within square
brackets. For example, list1 and list2 shown below contains a single type of data.

Here, list1 has integers while list2 has strings. Lists can also store mixed data types as shown in the
list3 here.

Storing a list in a static data structure (Array List)


This implementation stores the list in an array. The position of each element is given by an index from
0 to n-1, where n is the number of elements. Given any index, the element with that index can be
accessed in constant time – i.e. the time to access does not depend on the size of the list. To add an
element at the end of the list, the time taken does not depend on the size of the list. However, the
time taken to add an element at any other point in the list does depend on the size of the list, as all
subsequent elements must be shifted up. Additions near the start of the list take longer than additions
near the middle or end. When an element is removed, subsequent elements must be shifted down, so
removals near the start of the list take longer than removals near the middle or end.

Storing a list in a dynamic data structure (Linked List)


The Link List is stored as a sequence of linked nodes. As in the case of the stack and the queue,
each node in a linked list contains data AND a reference to the next node. The list can grow and
shrink as needed. The position of each element is given by an index from 0 to n-1, where n is the
number of elements. Given any index, the time taken to access an element with that index depends
on the index. This is because each element of the list must be traversed until the required index is
found. The time taken to add an element at any point in the list does not depend on the size of the
list, as no shifts are required. It does, however, depend on the index. Additions near the end of the list
take longer than additions near the middle or start. The same applies to the time taken to remove an
element. The first node is accessed using the name LinkedList.head Its data is accessed using
LinkedList.Head.DataItem The second node is accessed using LinkedList.Head.NextNode.

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 1


ARRAY IMPLEMENTATION OF LISTS:
A list is a sequential data structure, i.e. a collection of items accessible one after another beginning at
the head and ending at the tail.
It is a widely used data structure for applications which do not need random access, Addition and
removals can be made at any position in the list
Lists are normally in the form of a1, a2, a3.....an. The size of this list is n. The first element of the list
is a1, and the last element is a’n. The position of element a; in a list is i. List of size 0 is called as null
list.

Basic Operations on a List

• Creating a list
• Traversing the list
• Inserting an item in the list
• Deleting an item from the list
• Concatenating two lists into one

Implementation of List:

A list can be implemented in two ways


1. Array list
2. Linked list

1. Storing a list in a static data structure (Array List)


This implementation stores the list in an array. The position of each element is given by an index from
0 to n-1, where n is the number of elements. The element with the index can be accessed in constant
time (ie) the time to access does not depend on the size of the list. The time taken to add an element
at the end of the list does not depend on the size of the list. But the time taken to add an element at
any other point in the list depends on the size of the list because the subsequent elements must be
shifted to next index value.
• So the additions near the start of the list take longer time than the additions near the middle or
end.
• Similarly when an element is removed, subsequent elements must be shifted to the previous
index value. So removals near the start of the list take longer time than removals near the
middle or end of the list.

Problems with Array implementation of lists:

• Insertion and deletion are expensive. For example, inserting at position 0 (a new first element)
requires first pushing the entire array down one spot to make room, whereas deleting the first
element requires shifting all the elements in the list up one, so the worst case of these
operations is O(n).
• Even if the array is dynamically allocated, an estimate of the maximum size of the list is
required. Usually this requires a high over-estimate, which wastes considerable space. This
could be a serious limitation, if there are many lists of unknown size.
[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 2
• Simple arrays are generally not used to implement lists. Because the running time for insertion
and deletion is so slow and the list size must be known in advance

2. Storing a list in a dynamic data structure (Linked List)


• The Linked List is stored as a sequence of linked nodes which are not necessarily adjacent in
memory.
• Each node in a linked list contains data and a reference to the next node, The list can grow
and shrink in size during execution of a program.
• The list can be made just as long as required. It does not waste memory space because
successive elements are connected by pointers.
• The position of each element is given by an index from 0 to n-1, where n is the number of
elements.
• The time taken to access an element with an index depends on the index because each
element of the list must be traversed until the required index is found.
• The time taken to add an element at any point in the list does not depend on the size of the list,
as no shifts are required
• Additions and deletion near the end of the list take longer than additions near the middle or
start of the list. Because the list must be traversed until the required index is found

Array versus Linked Lists


1. Arrays is suitable for
• Randomly accessing any element.
• Searching the list for a particular value
• Inserting or deleting an element at the end.

2. Linked lists are suitable for


• Inserting/Deleting an element.
• Applications where sequential access is required.
• In situations where the number of elements cannot be predicted beforehand.

LINKED LIST IMPLEMENTATION OF LISTS (POINTERS)


The Linked List is stored as a sequence of linked nodes which are not necessarily adjacent in
memory. Each node in a linked list contains data and a reference to the next node The list can grow
and shrink in size during execution of a program.
In the array implementation,
1. We are constrained to use contiguous space in the memory
2. Insertion, deletion entail shifting the elements

Pointers overcome the above limitations at the cost of extra space for pointers.
Data structure that will be used for the nodes. For list where each node holds a float: example, the
following struct could be used to create a

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 3


struct Node
{
int data ;
struct Node *next;
};

Introduction to Linked List:


If the memory is allocated before the execution of the program, It is fixed and can’t be
changed. We have to adopt an alternative strategy to allocate memory only when it is required. This
problem is overcome by a special data structure is called linked list.
For stack and queue we declare the size at the first to insert the data but sometimes situation may
occur not to utilize the full resources, this is waste of memory.
In computer science, a linked list is one of the fundamental data structure. Linked list are special list
of some data element. Each element is called node. Each node has two parts one is called
information part which stores the information and another is pointer which points to the next elements.

Advantages of linked list:-


➢ Linked list are dynamic data structure. That is they can grow and shrink during the execution of
a program.
➢ Efficient memory utilization. Here, memory is not pre-allocated, memory is allocated whenever
it is no longer needed.
➢ Insertion and deletion are easier and efficient linked list provide flexibility in inserting a data
item at a specified position and deletion of item from the given position.

Disadvantages of linked list:-


➢ More memory: - if the numbers of fields are more, then more memory space is required.
➢ Access to an arbitrary data item is little bit cumbersome and also consuming.

Linked List as an ADT:


➢ A linked list is a chain of nodes where each node in the list consists of two fields, a data field
and a next address field.
➢ The data field holds the actual element on the list where the next address field contains the
address of next node in the list. Hence, the next address field is simply a reference to the next
node.

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 4


➢ The entire linked list is accessed from the reference variable first that points to the first node in
the list.
➢ The next address field of the last node in the list contains a special value known as null, which
is not a valid address. The value null is used to signal end of the list.
➢ The list with no nodes is called as empty list or null list. In such cases, the value of pointer
first=null. Moreover, a linked list is initialized to empty list by the operation first=null.
➢ A linked list is a dynamic data structure. The number of nodes in the list may vary as elements
are inserted or removed.
➢ Just like a stack or queue, a linked list in itself is a data structure. The data field of each node
stores the actual information we can apply several operations on the list. Some of the most
common operations include insertion of nodes, deletion of nodes, list traversal etc.

Operations of Linked List:


a. Creation b. Insertion c. Searching d. Deletion e. Traversing f. Concatenation g. Display

Insertion:-
➢ This operation is used to insert a new node in the linked list at the specified position. New
node may be inserted:-
➢ At the beginning of the linked list
➢ At the end of the linked list
➢ At the specified position in a linked list
➢ If the list itself is empty, then new node is inserted as a first node.

Searching:-
The process of locating the node is called searching a node.

Deletion:-
This operation is used to delete an item (a node) from the linked list. A node may be deleted from:
➢ Beginning of a linked list
➢ End of the linked list
➢ Specified position in the list

Traversing:-
This is the process of going through all the nodes of a linked list from one end to another end. If we
start traversing form the very first node towards the last node, it is called forward traversing. If the
derived operation is found we signal operation “successful” otherwise, we signal it as “unsuccessful”.

Concatenation:-
It is the process of appending (joining) the second list to the end of first list consisting of M nodes.
The concatenated list will be having (M+N) nodes.

Display:-
This operation is used to print each and every nodes information.

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 5


Singly Linked List(SLL):
Singly linked lists contain nodes which have a data part as well as an address part i.e. next, which
points to the next node in the sequence of nodes.
The operations we can perform on singly linked lists are insertion, deletion and traversal.

Representation of Singly Linked List in Program:


struct Node {
int data;
struct Node* next;
};

Doubly Linked List(DLL):


In a doubly linked list, each node contains a data part and two addresses, one for the previous node
and one for the next node.

Representation of Doubly Linked List in Program:


struct Node {
int data;
struct Node *next;
struct Node *prev;
};

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 6


Circular Linked List(CLL):
In circular linked list the last node of the list holds the address of the first node hence forming a
circular chain.

Doubly Circular Linked List(DCLL):


Circular Doubly Linked List has properties of both doubly linked list and circular linked list in which
two consecutive elements are linked or connected by the previous and next pointer and the last node
points to the first node by the next pointer and also the first node points to the last node by the
previous pointer.

Linked List Implementation:


Before start the implementation of linked you must know:
> what is List and Dynamic List?
> what is dynamic memory allocation and how to use malloc() function in C programming
> what is structure data type in c language and how to access the structure members using
pointers
> what is pointer and how to use pointer in c programming.

Full Program of Dynamic Linked List Implementation – (Creating Singly Linked List):
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
//clrscr();
//step 1: Creating structure:
struct node

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 7


{
int data;
struct node *next;
};
struct node *head, *newnode, *temp;
head=0;
int choice;
do
{
//creating node using using malloc( ) function
newnode=(struct node *) malloc(sizeof(struct node));

//step 3: Ask user to insert value


printf("enter the number to insert: ");
scanf("%d",&newnode->data);
newnode->next=0;

if(head==0)
{
head=newnode;
temp=newnode;
}
else
{
temp->next=newnode;
temp=newnode;
}
printf("Do you want to continue(0=Exit,1=Continue)?");
scanf("%d",&choice);
}while(choice);

temp=head; //to display node from first entry, temp was stored address of last node
printf(" %p\n",head); //to print address of HEAD
while(temp!=0)
{
printf("[%d | %p]\n",temp->data, temp->next);
temp=temp->next;
}
getch();
return 0;
}

Output:

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 8


Insertion Operation in Linked List:
Insertion of Node at Beginning:
• Allocate memory for new node
• Store data
• Change next of new node to point to head
• Change head to point to recently created node

An algorithm to insert a node at the beginning of the singly linked list:


1. Start
2. Create a new node using malloc function as,
newnode=(NodeType *)malloc(sizeof(NodeType));
3. Read data item to be inserted say ‘element’
4. Assign data to the info field of new node
newnode.data=element;
5. Set next of new node to first
newnode.next=head;
6. Set the head pointer to the new node
head=newnode;
7. End

//Inserting node at beginning of list


struct node
{

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 9


int data;
struct node *next;
};
void insertAtBeginning()
{
struct node *head, *newnode;
newnode=(struct node *)malloc(sizeof(struct node));
printf("enter data u want to insert:");
scanf("%d",&newnode->data);
newnode->next=head;
head=newnode;
}

Full program in c to Insert Node at Beginning of List:


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node {
int data; // Data
struct node *next; // Address
};
struct node *head;

void createList(int n);


void insertNodeAtBeginning(int data);
void displayList();

void main()
{
int n, data;
//clrscr();
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);
printf("\nData in the list \n");
displayList();

printf("\nEnter data to insert at beginning of the list: ");


scanf("%d", &data);
insertNodeAtBeginning(data);

printf("\nData in the list \n");


displayList();
}
void createList(int n)
{
struct node *newNode, *temp;
int i;
head=0;

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 10


newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data of node 1: ");
scanf("%d", &newNode->data);
newNode->next = 0; // Link address field to NULL
if(head==0)
{
head=temp=newNode;
}
else
{
temp->next=newNode;
temp=newNode;
}
//Create n nodes and adds to linked list
for(i=1; i<n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data of node %d: ", i);
scanf("%d", &newNode->data);
newNode->next = 0; // Link address field of newNode with NULL
temp->next = newNode; // Link temp to the newNode
temp = newNode;
}
printf("SINGLY LINKED LIST CREATED SUCCESSFULLY\n");
}
void insertNodeAtBeginning(int data)
{
struct node *newNode;
newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data; // Link data part
newNode->next = head; // Link address part
head = newNode; // Make newNode as first node

printf("DATA INSERTED SUCCESSFULLY\n");


}
void displayList()
{
struct node *temp;
temp = head;
printf("Head Address = %p\n",head);
while(temp != NULL)
{
printf("Data at %p= %d |\t Next = %p\n",temp, temp->data,temp->next); // Print data of
current node
temp = temp->next; // Move to next node
}
getch();
}

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 11


Insertion of Node at End:

Algorithm to insert a ned at the end of the linked list:


1. Start
2. Create a new node using malloc function as,
newnode=(NodeType *)malloc(sizeof(NodeType));
3. Read data item to be inserted say ‘element’
4. Assign data to the info field of new node
newnode.data=element;
5. Set next of new node to null
newnode.next=NULL;
6. If(head==null) then
Set, head=temp=newnode and exit
7. else
set, temp->next=newnode;
set, temp=newnode;
8. End

//Insertion of node at End of List


struct node
{
int data;
struct node *next;
};
void InsertAtEnd()
{
struct node *head, *newnode, *temp;
newnode=(struct node *)malloc(sizeof(struct node));
printf("enter data u want to insert:");
scanf("%d",&newnode->data);
newnode->next=0;
temp=head;
while(temp->next!=0)
{
temp=temp->next;
}
temp->next=newnode
}

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 12


Full Program in C to Insert Node at End of List
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node {
int data; // Data
struct node *next; // Address
};
struct node *head;

void createList(int n);


void insertNodeAtLast();
void displayList();

void main()
{
int n, data;
//clrscr();
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);
printf("\nData in the list \n");
displayList();

//printf("\nEnter data to insert at Last index of the list: ");


//scanf("%d", &data);
insertNodeAtLast();

printf("\nData in the list \n");


displayList();
}
void createList(int n)
{
struct node *newNode, *temp;
int i;
head=0;
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data of node 1: ");
scanf("%d", &newNode->data);
newNode->next = 0; // Link address field to NULL
if(head==0)
{
head=temp=newNode;
}
else
{
temp->next=newNode;
temp=newNode;
}
//Create n nodes and adds to linked list
for(i=1; i<n; i++)

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 13


{
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data of node %d: ", i);
scanf("%d", &newNode->data);
newNode->next = 0; // Link address field of newNode with NULL
temp->next = newNode; // Link temp to the newNode
temp = newNode;
}
printf("SINGLY LINKED LIST CREATED SUCCESSFULLY\n");
}
void insertNodeAtLast()
{
int data;
struct node *newnode, *temp;
newnode=(struct node *)malloc(sizeof(struct node));
printf("enter data to insert at the END:");
scanf("%d",&newnode->data);
newnode->next=0;
temp=head;
while(temp->next!=0)
{
temp=temp->next;
}
temp->next=newnode;
printf("DATA INSERTED SUCCESSFULLY\n");

}
void displayList()
{
struct node *temp;
temp = head;
printf("Head Address = %p\n",head);
while(temp != NULL)
{
printf("Data at %p= %d |\t Next = %p\n",temp, temp->data,temp->next); // Print
data of current node
temp = temp->next; // Move to next node
}
getch();
}

Inserting node at a specified position in a singly linked list:

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 14


Algorithm to insert element at the specified position
1. Start
2. Create a new node using malloc function as,
newnode=(NodeType *)malloc(sizeof(NodeType));
3. Read data item to be inserted say ‘element’
4. Assign data to the info field of new node
newnode.data=element;
5. Set next of new node to first
Newnode->next=temp->next;
6. Set the head pointer to the new node
Temp->next=newnode;
7. End

void insertNodeAtGivenPosition()
{
int data, pos, i;
struct node *newnode, *temp;
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the position of a node at which you want to insert a new node: ");
scanf("%d",&pos);
printf("enter data to insert at the Nth Position:");
scanf("%d",&newnode->data);
temp=head;
for(i=1;i<pos-1;i++)
{
temp=temp->next;
}
newnode->next=temp->next;
temp->next=newnode;

printf("DATA INSERTED SUCCESSFULLY\n");

Full Program in C to Insert Node at given N’th position:


//Program to insert node in given position
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node {
int data; // Data
struct node *next; // Address
};
struct node *head;

void createList(int n);


void insertNodeAtGivenPosition();
void displayList();
[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 15
void main()
{
int n, data;
//clrscr();
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);
printf("\nData in the list \n");
displayList();

//printf("\nEnter data to insert at Last index of the list: ");


//scanf("%d", &data);
insertNodeAtGivenPosition();

printf("\nData in the list \n");


displayList();
}
void createList(int n)
{
struct node *newNode, *temp;
int i;
head=0;
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data of node 1: ");
scanf("%d", &newNode->data);
newNode->next = 0; // Link address field to NULL
if(head==0)
{
head=temp=newNode;
}
else
{
temp->next=newNode;
temp=newNode;
}
//Create n nodes and adds to linked list
for(i=1; i<n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data of node %d: ", i);
scanf("%d", &newNode->data);
newNode->next = 0; // Link address field of newNode with NULL
temp->next = newNode; // Link temp to the newNode
temp = newNode;
}
printf("SINGLY LINKED LIST CREATED SUCCESSFULLY\n");
}
void insertNodeAtGivenPosition()
{
int data, pos, i;

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 16


struct node *newnode, *temp;
newnode=(struct node *)malloc(sizeof(struct node));

printf("\nEnter the position of a node at which you want to insert a new node: ");
scanf("%d",&pos);

printf("enter data to insert at the Nth Position:");


scanf("%d",&newnode->data);

temp=head;
for(i=1;i<pos-1;i++)
{
temp=temp->next;
}
newnode->next=temp->next;
temp->next=newnode;

printf("DATA INSERTED SUCCESSFULLY\n");

}
void displayList()
{
struct node *temp;
temp = head;
printf("Head Address = %p\n",head);
while(temp != NULL)
{
printf("Data at %p= %d |\t Next = %p\n",temp, temp->data,temp->next); // Print data of
current node
temp = temp->next; // Move to next node
}
getch();
}

Deletion Operation in Linked List:


Deleting Node at the Beginning of List:
• If head is NULL, return. There is no element in the linked list.
• Assign the head pointer to a temporary variable, tmp.
• Move the head to the next node. If the linked list has only one node, head will move to NULL.
• Delete the temporary pointer, tmp. As tmp is pointing to the first node, first node will be
deleted.

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 17


Algorithm to delete the node from beginning
Let ‘head’ and ‘last’ are the pointer to first node and last node in the current list respectively
1. Start
2. If(head==null) then
Print “No node available”
3. Else if (head==last)
Print deleted item as head->data
Head=last=null;
4. Store the address of first node in temporary variable temp
Set temp=head;
5. Set head to next of first
Set, head=head->next;
6. Free the memory reserved by temp variable
Free(temp);
7. End

//Deletion of Node at Beginning


struct node
{
int data;
struct node *next;
};
struct node *head, *tmep;
deleteFromBeg()
{
temp=head;
head=head->next;
free(temp);
}

Full Program in C to Delete Node at the Beginning of List


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
/* Structure of a node */
struct node {
int data; // Data
struct node *next; // Address
};
[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 18
struct node *head, *temp;

void createList(int n);


void DeleteNodeAtBeginning();
void displayList();

void main()
{
int n, data;
//clrscr();
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);

printf("\nData in the list \n");


displayList();

printf("\nPress 1 to delete at beginning of the list: ");


scanf("%d", &data);
DeleteNodeAtBeginning();

printf("\nData in the list After Deletion \n");


displayList();
}
void createList(int n)
{
struct node *newNode;
int i;
head=0;

newNode = (struct node *)malloc(sizeof(struct node));


printf("Enter the data of node 1: ");
scanf("%d", &newNode->data);
newNode->next = 0; // Link address field to NULL

if(head==0)
{ head=temp=newNode; }
else
{
temp->next=newNode;
temp=newNode;
}
//Create n nodes and adds to linked list
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data of node %d: ", i);
scanf("%d", &newNode->data);
newNode->next = 0; // Link address field of newNode with NULL
temp->next = newNode; // Link temp to the newNode
temp = newNode;

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 19


}
printf("SINGLY LINKED LIST CREATED SUCCESSFULLY\n");
}
void DeleteNodeAtBeginning()
{
temp=head;
head=head->next;
free(temp);

printf("DATA Deleted SUCCESSFULLY\n");


}
void displayList()
{
temp = head;
printf("Head= %p\n",head);
while(temp != NULL)
{
printf("Data at %p = %d | Next = %p \n", temp,temp->data,temp->next); // Print
data of current node
temp = temp->next; // Move to next node
}
getch();
}

Deleting Node at the End of List:


• If head points to NULL, return. The linked list is empty – there is no node.
• If the first node points to NULL – there is only one node in the linked list, delete the first node
and assign NULL to head.
• Point prev to first node and cur to second node.
• Keep moving prev and cur (prev = prev->next, cur = cur->next) until cur->next is NULL.
• If cur->next is NULL, set prev->next equals to NULL and delete cur

Algorithm to delete the node from the end


Let ‘head’ and ‘last’ are the pointer to first node and last node in the current list respectively
1. Start
2. If(head==null) then
Print “No node available”
3. Else if (head==last)
Print deleted item as head->data
Head=last=null;
4. Else
While(temp->next != last)

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 20


Set temp=temp->next;
Set, temp->next=null;
Set, last=temp;
5. End

//Deletion of Node at End of the List


struct node
{
int data;
struct node *next;
};
deleteFromEnd()
{
struct node *prevNode;
temp=head;
while(temp->next!=0)
{
prevNode=temp;
temp=temp->next;
}
if(temp==head)
{ head=0; }
else
{ prevNode->next=0; }
free(temp);
}

Full Program in C to Delete Node at End of List:


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
/* Structure of a node */
struct node {
int data; // Data
struct node *next; // Address
};
struct node *head, *temp;

void createList(int n);


void DeleteNodeAtEnd();
void displayList();

void main()
{
int n, data;

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 21


clrscr();
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);

printf("\nData in the list \n");


displayList();

//Delete data at the beginning of the singly linked list


printf("\nPress 1 to delete at END of the list: ");
scanf("%d", &data);
DeleteNodeAtEnd();

printf("\nData in the list After Deletion \n");


displayList();
}

void createList(int n)
{
struct node *newNode;
int i;
head=0;

newNode = (struct node *)malloc(sizeof(struct node));


printf("Enter the data of node 1: ");
scanf("%d", &newNode->data);
newNode->next = 0; // Link address field to NULL

if(head==0)
{ head=temp=newNode; }
else
{
temp->next=newNode;
temp=newNode;
}
//Create n nodes and adds to linked list
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data of node %d: ", i);
scanf("%d", &newNode->data);
newNode->next = 0; // Link address field of newNode with NULL
temp->next = newNode; // Link temp to the newNode
temp = newNode;

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 22


}
printf("SINGLY LINKED LIST CREATED SUCCESSFULLY\n");
}

//* Create a new node and inserts at the beginning of the linked list.
void DeleteNodeAtEnd()
{
struct node *prevNode;
temp=head;
while(temp->next!=0)
{
prevNode=temp;
temp=temp->next;
}
if(temp==head)
{ head=0; }
else
{ prevNode->next=0; }
free(temp);
printf("DATA Deleted SUCCESSFULLY\n");
}

// * Display entire list


void displayList()
{
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print data of current node
temp = temp->next; // Move to next node
}
getch();
}

Algorithm to delete the node from given position:


Let ‘head’ and ‘last’ are the pointer to first node and last node in the current list respectively
1. Start
2. If(head==null) then
Print “No node available”
3. else
Enter position of a node at which you want to delete a new node as - pos
4. Set, temp=head
5. For (i=1; i<pos-1; i++)
Set, temp=temp->next
6. Print deleted item is , temp→next-> data
[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 23
7. Set, loc=temp-> next
8. Set, temp->next = loc->next
9. end

Searching an item in a linked list


void searchItem(int key)
{
NodeType *temp;
if(head==null)
{
printf(“Empty Linked List”);
exit(0);
}
else
{
temp=head;
while(temp != null)
{
if(temp -> data == key )
{
Printf(“Searched item found”);
}
temp = temp -> next;
}
if(temp == null)
printf(“Item not found”);
}
}

Implementation of Stack using Linked List:

Full program in C to implement dynamic stack using linked list:

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

struct node
{
[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 24
int data;
struct node *next;
};
struct node *top=0;
void push(int x)
{
struct node *newnode;
newnode=(struct node *)malloc(sizeof(struct node));
newnode->next=top;
newnode->data=x;
top=newnode;
}
void display()
{
struct node *temp;
temp=top;
if(top==0)
{ printf("Stack is Empty"); }
else
{
while(temp!=0)
{
printf("\nStack value: %d",temp->data);
temp=temp->next;
}
}
}
void peek()
{
if(top==0)
{ printf("\nStack is Empty"); }
else
{
printf("\n Top Element of stack is: %d",top->data);
}
}
void pop()
{
struct node *temp;
temp=top;
printf("\n Deleted item of stack is: %d",temp->data);
top=top->next;
free(temp);
}

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 25


void main()
{ int ch, n;
clrscr();
do
{
printf("\n Choose Operation - 1 Push, 2 Pop, 3 Display, 4 Peek: ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Insert into stack: ");
scanf("%d",&n);
push(n);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: peek();
break;
default:printf("Invallid choice");
break;
}
} while(ch!=0);
getch();
}

Implementation of Queue using Linked List (Dynamic Implementation):

Implementing a queue using a linked list allows us to grow the queue as per the requirements, i.e.,
memory can be allocated dynamically. A queue implemented using a linked list will not change its
behaviour and will continue to work according to the FIFO principle.

Steps for implementing queue using linked list:


[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 26
1. Enqueue Function

Enqueue function adds an element to the end of the queue. It takes O(1) time. The last element can
be tracked using the rear pointer.

• First, build a new node with given data.


• Check if the queue is empty or not.
• If a queue is empty then, a new node is assigned to the front and rear.
• Else make next of rear as new node and rear as a new node.

2. Dequeue Function

The dequeue function always removes the first element of the queue. It takes O(1) time. For
dequeue, the queue must contain at least one element, else underflow conditions will occur.

• Check if queue is empty or not.


• If the queue is empty, then dequeue is not possible.
• Else store front in temp
• And make next of front as the front.
• Delete temp, i.e, free(temp).

3. Print

Print function is used to display the content of the queue. Since we need to iterate over each element
of the queue to print it, the time complexity of the print function is O(n), where n = number of nodes in
a queue.

• Check if queue contains at least one element or not.


• If the queue is empty print “No elements in the queue.”
• Else, define a node pointer and initialize it with the front.
• Display data of node pointer until the next node pointer becomes NULL.

Implementation of queue using linked list in C


#include<stdio.h>
#include <stdlib.h>
// Structure to create a node with data and the next pointer
struct node {
int data;
struct node *next;
};

struct node *front = NULL;


struct node *rear = NULL;

// Enqueue() operation on a queue


void enqueue(int value) {
struct node *newNode;

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 27


newNode = (struct node *) malloc(sizeof(struct node));
newNode -> data = value;
newNode -> next = NULL;
if ((front == NULL) && (rear == NULL)) {
front = newNode;
rear = newNode;
}
else {
rear -> next = newNode;
rear = newNode;
}
printf("Node is Inserted\n\n");
}

// Dequeue() operation on a queue


int dequeue() {
int temp_data;
if (front == NULL) {
printf("\nUnderflow\n");
return -1;
}
else
{
struct node *temp = front;
temp_data = front -> data;
front = front -> next;
free(temp);
return temp_data;
}
}

// Display all elements of the queue


void display() {
struct node *temp;
if ((front == NULL) && (rear == NULL)) {
printf("\nQueue is Empty\n");
}
else
{
printf("The queue is \n");
temp = front;
while (temp!=0) {
printf("%d--->", temp -> data);
temp = temp -> next;
}
printf("NULL\n\n");
}
}

int main() {
int ch, value;

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 28


printf("\nImplementation of Queue using Linked List\n");
while (ch!= 4) {
printf("1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\n");
printf("\nEnter your choice : ");
scanf("%d", & ch);
switch (ch) {
case 1:
printf("\nEnter the value to insert: ");
scanf("%d", & value);
enqueue(value);
break;
case 2:
printf("Popped element is :%d\n", dequeue());
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nWrong Choice\n");
}
}
return 0;
}

Circular Linked List


A circular linked list is basically a linear linked list that may be singly or doubly. The only difference is
that there is no any NULL value terminating the list. In fact in the list every node points to the next
node and last node points to the first node, thus forming a circle. Since it forms a circle with no end to
stop hence it is called as circular linked list.

In circular linked list there can be no starting or ending node, whole node can be traversed from any
node. In order to traverse the circular linked list only once we need to traverse entire list until the
starting node is not traversed again.

A circular linked list can be implemented using both singly linked list and doubly linked list. Here is the
logical structure of a circular linked list.

Basic structure of Circular linked list

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 29


Singly Circular Linked List

Doubly Circular Linked List

Implementation of Singly Circular Linked List:


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

struct node {
int data;
struct node *next;
}*head;

void createCircularList(int n);


void displayList();

void main(){
int n,d;
printf("Enter how many records do you want to insert: ?");
scanf("%d",&n);
createCircularList(n);
printf("\nData in the List = ");
displayList();

void createCircularList(int n)
{
struct node *newNode, *temp;
int i;
head=0;

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 30


newNode=(struct node *)malloc(sizeof(struct node));
printf("Enter the data of node 1: ");
scanf("%d",&newNode->data);
newNode->next=0;

if(head==0)
{
head=newNode;
temp=newNode;
}
else{
temp->next=newNode;
temp=newNode;
}
//creating n nodes and add to linked list
for(i=2;i<=n;i++)
{
newNode=(struct node *)malloc(sizeof(struct node));
printf("Enter the data of node %d ",i);
scanf("%d",&newNode->data);
newNode->next=0;
temp->next=newNode;
temp=newNode;
}
temp->next=head;
printf("\nSINGLY LINKED LIST CREATED SUCCESSFULLY");
}

void displayList()
{
struct node *temp;
temp=head;
printf("\nHead=%p\n",head);
while(temp->next!=head)
{
printf("[Data: %d | %p : Address]\n",temp->data,temp->next);
temp=temp->next;
}
printf("[Data: %d | %p : Address]\n",temp->data,temp->next);
}

Doubly Linked List

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 31


In a linked List, we have a head node, which points to the first Node in the Linked List, and then we
have the Null at the end, marking the end of the Linked list. To transverse the list completely, we
need to start from the head till the Null.

If you would look carefully, in any LinkedList, it is not easy to go to the previous Element. E.g. if we
have a LinkedList = 1 → 2 → 3, then we can traverse it from 1 to 2 and from 2 to 3, following the Next
pointers, but what if we want to go back to 1 from 2?

What is Doubly Linked List?


Doubly Linked List is a Data Structure, which is a variation of the Linked List, in which the transversal
is possible in both the directions, forward and backward easily as compared to the Singly Linked List,
or which is also simply called as a Linked List. You might be aware of the Tabs in Windows/Mac. You
can basically loop over all the opened applications, and can switch between these applications in
both the directions.

So if a Linked List ⇒ A → B →. C

Then a Doubly Linked List ⇒ A ⇆ B ⇆ C

C Program to implement doubly linked list:


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

struct node {
int data;
struct node *next;
struct node *prev;
}*head, *newNode;

void create(int n);

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 32


void displayList();

void main(){
int n,d;
printf("Enter how many records do you want to insert: ?");
scanf("%d",&n);
create(n);
printf("\nData in the List = ");
displayList();

void create(int n)
{
struct node *temp;
int i;
head=0;
newNode=(struct node *)malloc(sizeof(struct node));
printf("Enter the data of node 1: ");
scanf("%d",&newNode->data);
newNode->next=0;
newNode->prev=0;
if(head==0)
{
head=newNode;
temp=newNode;
}
else{
temp->next=newNode;
newNode->prev=temp;
temp=newNode;
}
//creating n nodes and add to linked list
for(i=2;i<=n;i++)
{
newNode=(struct node *)malloc(sizeof(struct node));
printf("Enter the data of node %d : ",i);
scanf("%d",&newNode->data);
newNode->next=0;
temp->next=newNode;
newNode->prev=temp;
temp=newNode;
}
printf("\nDOUBLY LINKED LIST CREATED SUCCESSFULLY");

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 33


}

void displayList()
{
struct node *temp;
temp=head;
printf("\nHead=%p\n",head);
while(temp!=0)
{
printf("[PREV: %p | Data: %d | %p : NEXT]\n",temp->prev,temp->data,temp->next);
temp=temp->next;
}
}

Algorithm for Insertion and Deletion Operation:


Assume that START is the first element in the linked list and TAIL is the last element of linked list.
i. Insert At Beginning
1. Start
2. Input the DATA to be inserted
3. Create a new node.
4. NewNode → Data = DATA,
NewNode →Lpoint =NULL
5. IF START IS NULL, NewNode→ Rpoint = NULL
6. Else NewNode → Rpoint = START,
START→Lpoint = NewNode
7. START =NewNode
8. Stop

ii. Insert at End


1. Start
2. Input DATA to be inserted
3. Create a NewNode
4. NewNode → DATA = DATA
5. NewNode → RPoint = NULL
6. If (SATRT equal to NULL)
a. START = NewNode
b. NewNode → LPoint=NULL
7. Else
a. TEMP = START
b. While (TEMP → Next not equal to NULL)
TEMP = TEMP → Next
c. TEMP → RPoint = NewNode

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 34


d. NewNode → LPoint = TEMP
8. Stop

iii. Forward Traversal


1. Start
2. If (START is equal to NULL)
a) Display “The list is Empty”
b) Stop

3. Initialize TEMP = START


4. Repeat the step 5 and 6 until (TEMP == NULL )
5. Display “TEMP → DATA”
6. TEMP = TEMP → Next
7. Stop

iv. Backward Traversal


1. Start
2. If (START is equal to NULL)
3. Display “The list is Empty”
4. Stop
5. Initialize TEMP = TAIL
6. Repeat the step 7 and 8 until (TEMP == NULL )
7. Display “TEMP → DATA”
8. TEMP = TEMP → Prev
9. Stop

Doubly Circular LinkedList (DCLL):

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

struct node {
int data;
struct node *next;
struct node *prev;
}*head, *newNode;

void create(int n);


void displayList();

void main(){
int n,d;
printf("Enter how many records do you want to insert: ?");
scanf("%d",&n);

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 35


create(n);
printf("\nData in the List = ");
displayList();

void create(int n)
{
struct node *temp;
int i;
head=0;
newNode=(struct node *)malloc(sizeof(struct node));
printf("Enter the data of node 1: ");
scanf("%d",&newNode->data);
newNode->next=0;
newNode->prev=0;
if(head==0)
{
head=newNode;
temp=newNode;
}
/*
else{
temp->next=newNode;
newNode->prev=temp;
temp=newNode;
}
*/
//creating n nodes and add to linked list
for(i=2;i<=n;i++)
{
newNode=(struct node *)malloc(sizeof(struct node));
printf("Enter the data of node %d : ",i);
scanf("%d",&newNode->data);
newNode->next=0;
temp->next=newNode;
newNode->prev=temp;
temp=newNode;
}
temp->next=head;
head->prev=temp;
printf("\nDOUBLY LINKED LIST CREATED SUCCESSFULLY");
}

void displayList()
{
struct node *temp;
temp=head;
printf("\nHead=%p\n",head);
while(temp->next !=head )
{

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 36


printf("[PREV: %p | CURRENT '%p' = Data: %d | %p : NEXT]\n",temp-
>prev,temp,temp->data,temp->next);
temp=temp->next;
}
printf("[PREV: %p | CURRENT '%p' = Data: %d | %p : NEXT]\n", temp->prev,temp,temp-
>data,temp->next);
}

Note: Additional link for doubly linked list:

https://prepinsta.com/data-structures/doubly-linked-list-in-c/

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 37

You might also like