linkedlist2
linkedlist2
linkedlist2
UNIT-2
Dr. Nagarathna
N
PROFESSOR
B.M.S. COLLEGE OF ENGINEERING
UNIT 2 : LINKED LIST
Dr. Nagarathna
N
PROFESSOR
B.M.S. COLLEGE OF ENGINEERING
UNIT 2
• In music players, we can create our song playlist and can play a song either from
starting or ending of the list. And these music players are implemented using a
linked list.
• We watch the photos on our laptops or PCs, and we can simply see
the next or previous images easily. This feature is implemented using a linked list.
• You must be reading this article on your web browser, and in web browsers, we
open multiple URLs, and we can easily switch between those URLs using the
previous and next buttons because they are connected using a linked list.
Types of Linked Lists
• Singly Linked List
• Doubly Linked List
• Circular Linked
List
Singly Linked List
• 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.
Doubly Linked List
• 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.
Circular Linked List
• In circular linked list the last node of the
list holds the address of the first node
hence forming a circular chain.
• Applications of Singly Linked List :
• The singly linked list is used to implement stack and queue.
• The undo or redo options, the back buttons, etc., that we discussed above are
implemented using a singly linked list.
• During the implementation of a hash function, there arises a problem of collision, to
deal with this problem, a singly linked list is used.
• Application of Doubly Linked Lists :
• The doubly linked list is used to implement data structures like a stack, queue, binary tree, and hash
table.
• It is also used in algorithms of LRU (Least Recently used) and MRU(Most Recently Used) cache.
• The undo and redo buttons can be implemented using a doubly-linked list.
• The doubly linked list can also be used in the allocation and deallocation of memory.
• Applications of Circular Linked Lists :
• The circular linked list can be used to implement queues.
• In web browsers, the back button is implemented using a circular linked list.
• In an operating system, a circular linked list can be used in scheduling algorithms like
the Round Robin algorithm.
• The undo functionality that is present in applications like photo editors etc., is implemented
using circular linked lists.
• Circular linked lists can also be used to implement advanced data structures like MRU (Most
Recently Used) lists and Fibonacci heap.
Difference between Arrays and Linked List
Dynamic Memory Allocation Functions
Example
• Syntax for malloc():
ptr=(datatype *)malloc(specified-size);
• Example 1:
int *ptr; ptr=(int*)malloc(10*sizeof(int));
• Example 2:
struct *str;
str=(struct node*)malloc(sizeof(struct node));
NOTE: malloc and calloc functions return a void pointer, therefore, they can allocate a
memory for any type of data. They are used to allocate memory at run time.
Singly Linked List
• What is a Node?
• A Node in a linked list holds the data value
and the pointer which points to the location
of the next node in the linked list.
Node Implementation
// A linked list node struct (Self-referential structures: structure that
contain a reference to the data of its same type)
struct Node
{
int data;
struct Node *next;
};
16 2000 50 NULL
1000 2000
he
1000 2000
Current
Head
he
1000 2000 3000
Current1 Current2
Head
head->link=current1 current1->link=current2
head->link->link=current
Display the contents of the linked list
Make the first node of Linked List linked to the new node
Remove the head from the original first node of Linked List
Make the new node as the Head of the Linked List.
struct node {
int data;
struct node *next;
};
struct node *head = NULL, *current = NULL;
}
//insertion at the beginning
void insertatbegin(int data)
{
//create a new node
struct node *newnode = (struct node*) malloc(sizeof(struct node));
newnode->data = data;
void deleteatend()
{
struct node *linkedlist = head;
while (linkedlist->next->next != NULL)
linkedlist = linkedlist->next;
linkedlist->next = NULL;
}
[ 12 ->]
[ 22 -> 12 ->]
[ 22 -> 12 -> 30 ->]
[ 22 -> 12 -> 30 -> 44 ->]
[ 50 -> 22 -> 12 -> 30 -> 44 ->]
Linked List:
[ 50 -> 22 -> 12 -> 33 -> 30 -> 44 ->]
Linked List after deleting first node:
[ 22 -> 12 -> 33 -> 30 -> 44 ->]
Linked List after deleting last node
[ 22 -> 12 -> 33 -> 30 ->]
Linked List after deletion of given node 12
[ 22 -> 33 -> 30 ->]
Delete a node at the front
void Pop()
{
struct node *ptr;
if(head == NULL)
{
printf("\nList is empty");
}
else
{
ptr = head;
head = ptr->next;
free(ptr);
printf("\n Node deleted from the begining ...");
}
}
void end_delete()
Delete a node at the end
{
struct node *ptr,*ptr1;
if(head == NULL)
{
printf("\nlist is empty");
}
else if(head -> next == NULL)
{
free(head); head = NULL;
printf("\nOnly node of the list deleted ...");
}
else
{
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL; free(ptr);
printf("\n Deleted Node from the last ...");
}
}
Singly Linked List Implementation
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *next;
};
typedef struct node *NODE;
NODE insertFront(NODE first);
NODE insertRear(NODE first);
NODE insertAfter(NODE first);
NODE insertBefore(NODE first);
NODE insertAtPos(NODE first);
NODE deleteFront(NODE first);
NODE deleteRear(NODE first);
NODE deleteAfterEle(NODE first);
NODE deleteBeforeEle(NODE first);
NODE deleteElement(NODE first);
NODE deletePos(NODE first);
void display(NODE first);
*****Singly linked list implementation*****
Singly Linked List Implementation 1. Insert Front
void main() 2. Insert rear
{ 3. Insert After
4. Insert Before
NODE first=NULL; 5. Insert At Position
6. Delete Front
int choice;
7. Delete Rear
while(1) 8. Delete After
9. Delete Before
{ 10. Delete Element
printf("\n\n*****Singly linked list implementation*****"); 11. Delete At Position
12. Display
printf("\n 1. Insert Front \n 2. Insert rear \n 3. Insert After \n 13. Exit
4. Insert Before \n 5. Insert At Position \n ***********
Enter your choice
6. Delete Front \n 7. Delete Rear \n
8. Delete After \n 9. Delete Before \n 10. Delete Element \n
11. Delete At Position \n 12. Display \n 13. Exit");
printf("\n\t***********");
printf("\nEnter your choice ");
scanf("%d",&choice);
Singly Linked List Implementation
switch (choice)
{
case 1: first=insertFront(first); break;
case 2: first=insertRear(first); break;
case 3: first=insertAfter(first); break;
case 4: first=insertBefore(first); break;
case 5: first=insertAtPos(first); break;
case 6: first=deleteFront(first); break;
case 7: first=deleteRear(first); break;
case 8: first=deleteAfterEle(first); break;
case 9: first=deleteBeforeEle(first); break;
case 10: first=deleteElement(first); break;
case 11: first=deletePos(first); break;
case 12: display(first); break;
case 13: printf("\n Program exits now"); exit(0);
default: printf("enter valid choice");
}
}
}
Display
void display(NODE first)
{
NODE cur;
if(first==NULL)
printf("No elements to display");
else
{
cur=first;
printf("\n Elements of Singly linked list are:\t");
while(cur!=NULL)
{
printf("%d\t",cur->info);
cur=cur->next;
}
}
}
Insert in Front
NODE insertFront(NODE first)
{
NODE temp=NULL;
temp=(NODE)malloc(sizeof(struct node));
if (temp==NULL)
{
printf("Insufficient memory");
return first;
}
printf("\n Enter element to be inserted");
scanf("%d",&temp->info);
temp->next=NULL;
if(first==NULL)
first=temp;
else {
temp->next=first;
first=temp;
return first;
}
}
Insert at Rear
NODE insertRear(NODE first)
{
NODE temp=NULL,cur=NULL;
temp=(NODE)malloc(sizeof(struct node));
if (temp==NULL)
{
printf("Insufficient memory");
return first;
}
printf("\n Enter element to be inserted");
scanf("%d",&temp->info);
temp->next=NULL;
if(first==NULL)
first=temp;
else
{
cur=first;
while(cur->next!=NULL)
{
cur=cur->next;
}
cur->next=temp;
} return first; }
Insert After an item
NODE insertAfter(NODE first)
{
NODE temp=NULL,cur=NULL;
temp=(NODE)malloc(sizeof(struct node));
if (temp==NULL)
{
printf("Insufficient memory");
return first;
}
int ele,item;
if(first==NULL)
{
printf("linked list is empty");
return first;
}
printf("\n Enter element after which new node to be inserted");
scanf("%d",&ele);
Insert After an item Elements of Singly linked list are: 2 1 3
cur=first;
*****Singly linked list implementation*****
while(cur!=NULL&&cur->info!=ele) 1. Insert Front
cur=cur->next; 2. Insert rear
if(cur==NULL) 3. Insert After
4. Insert Before
{ 5. Insert At Position
printf("Element not found"); 6. Delete Front
return first; 7. Delete Rear
8. Delete After
}
9. Delete Before
printf("\nEnter element to be inserted"); 10. Delete Element
scanf("%d",&item); 11. Delete At Position
temp->info=item; 12. Display
13. Exit
temp->next=NULL; ***********
temp->next=cur->next; Enter your choice 3
cur->next=temp; Enter element after which new node to be inserted 1
return first; Enter element to be inserted5
2. Each Student should bring the lab record with the programs and output written for the programs completed in their
respective previous week and get it evaluated by the lab faculty in-charge. In the record book students should - Handwrite the
Program - Pasting of the printout of the Output or Handwriting of the Output (Output should be written for all the cases).
3. Continuous Internal Evaluation for each lab is for 10 marks which includes execution of the program in the allotted lab time
and showing the output. If Leetcode program is present for a particular lab, student needs to complete that also within the
allotted lab slot only and show the output. Observation book needs to be corrected on the same day itself.
Note: wherever LeetCode program is present, the program to be executed will be shared during the particular lab week.
Note: Submission during the lab slot: 10 marks
Submission on the same day but after lab slot: 8 marks
Submission within 1 week the program was assigned: 6 marks
Submission within 2 weeks the program was assigned: 5 marks
Submission any later: 0 marks
Lab Program
1. Write a program to implement Singly Linked List with following operations
a) Create a linked list.
b) Insertion of a node at first position, at any position and at end of list.
c) Display the contents of the linked list.
else
{
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL; free(ptr);
printf("\n Deleted Node from the last ...");
}
}
Delete a node at specified position
if(ptr == NULL)
{
printf("\nThere are less than %d elements in the
list..\n",loc);
return;
}
}
ptr1 ->next = ptr ->next;
free(ptr);
printf("\nDeleted %d node ",loc);
}
Singly Linked List Operations
• Search
• Count number of nodes
• Concatenation
• Merging
• Reversing
Search
Search for an element in the linked list:
•Initialize a node pointer, current = head.
•Do following while current is not NULL
•Get the key to be searched
• If the current value (i.e., current->data) is equal to the key being
searched return true.
•Otherwise, move to the next node (current = current->next).
•If the key is not found, return false
Search
Count number of nodes
void Count_nodes(struct node* head )
{
/* temp pointer points to head */
struct node* temp = head;
/* Initialize count variable */
int count=0;
/* Traverse the linked list and maintain the count */
while(temp != NULL)
{
temp = temp->next;
/* Increment count variable. */
count++;
}
/* Print the total count. */
printf("\n Total no. of nodes is %d",count);
}
Reversing
Lab Program 9: Write a program to implement Stack & Queues using Linked Representation.
Stack Implementation using Linked List
Stack Implementation using Linked List
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct
Node)); new_node->data = new_data;
new_node->next =
(*head_ref); (*head_ref) =
new_node;
}
void Pop()
{
struct node
*ptr; if(head ==
NULL)
{
printf("\nList is empty");
}
else
{
ptr = head;
head =
ptr->next;
free(ptr);
printf("\n Node deleted from the begining ...");
}
}
Queue implementation using Linked List
void Enqueue(item)
{
Queue implementation using Linked List
struct node *ptr,*temp;
}
Doubly Linked List
Doubly Linked List
Operations on Doubly Linked List
• Insertion at beginning
• Insertion at end
• Insertion after specified node
• Deletion at beginning
• Deletion at end
• Deletion of the node at given data
• Searching
• Traversing
Insertion at beginning
Insertion at beginning
void insertbeginning(int item)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->data=item;
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
head=ptr;
}
else
{
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr; head=ptr;
}
}
Insertion at end
void insertlast(int item)
{
Insertion at end
struct node *ptr = (struct node *) malloc(sizeof(struct node));
struct node *temp;
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL; ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr; ptr ->prev=temp;
ptr->next = NULL;
}
printf("\nNode Inserted\n");
}
Insert after specified node
void insert_specified(int item)
{
Insert after specified node
struct node *ptr = (struct node *)malloc(sizeof(struct node));
struct node *temp;
int i, loc;
printf("\nEnter the location\n");
scanf("%d",&loc);
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\ncan't insert\n");
return;
}
}
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp; temp->next = ptr;
temp->next->prev=ptr;
printf("Node Inserted\n");
} }
Deletion at beginning
Deletion at beginning
void beginning_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW\n");
}
else if(head->next == NULL)
{
head = NULL; free(head);
printf("\nNode Deleted\n");
}
else
{
ptr = head;
head = head -> next;
head -> prev = NULL; free(ptr);
printf("\nNode Deleted\n");
}
}
Deletion at end
void last_delete()
{
struct node *ptr;
Deletion at end
if(head == NULL)
{
printf("\n UNDERFLOW\n");
}
else if(head->next == NULL)
{
head = NULL; free(head);
printf("\nNode Deleted\n");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL; free(ptr);
printf("\nNode Deleted\n");
}
}
Deletion of a specified node
Deletion of a specified node
void delete_specified( )
{
struct node *ptr, *temp;
int val;
printf("Enter the value"); scanf("%d",&val);
temp = head;
while(temp -> data != val) temp = temp ->
next; if(temp -> next == NULL)
{
printf("\nCan't delete\n");
}
else if(temp -> next -> next == NULL)
{
temp ->next = NULL; printf("\nNode
Deleted\n");
}
else
{
ptr = temp -> next;
temp -> next = ptr -> next; ptr -> next -> prev =
temp; free(ptr);
printf("\nNode Deleted\n");
}
}
void search()
{
struct node *ptr; int item,i=0,flag; ptr = head;
if(ptr == NULL) Searching
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n"); scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("\nitem found at location %d ",i+1);
flag=0;
break;
}
else
{ flag=1; }
i++;
ptr = ptr -> next;
}
if(flag==1)
{printf("\nItem not found\n");}
}
}
Traversing
int traverse()
{
struct node *ptr;
if(head == NULL)
{
printf("\nEmpty List\n");
}
else
{
ptr = head;
while(ptr != NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
}
Lab Program
Lab Program 4: Write a program to Implement doubly linked list with
primitive operations
a) Create a doubly linked list.
b) Insert a new node to the left of the node.
c) Delete the node based on a specific value
d) Display the contents of the list
Useful Links
• https://visualgo.net/en/list?slide=1
• https://www.cs.usfca.edu/~galles/visualization/Algorithms.html
• https://csvistool.com