Linkedlist 1
Linkedlist 1
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