Deletion of node from last(end) in SLL

For delete the last node ,we need some extra effort to complete this task :

  • First we need some temporary variables to traverse the all node and reach at last node.
  • At last node we have to perform deletion operation.

Working Process

Code Implementation

#include <stdio.h>
#include<math.h>
#include<stdlib.h>
struct CreateNode   // Node Structure Initialization
{
    int  data;          // for data element
    struct CreateNode* nextNode;   //for storing the address of next element
};
struct CreateNode *HeadPointer=NULL;    // Initialization of HeadPointer
void deleteNodeAtEnd()   // Method of front Addition
{
    struct CreateNode* TempNode1=NULL;  // Create one TempNode 
    struct CreateNode* TempNode2=NULL;
    TempNode1=HeadPointer;
    while(TempNode1->nextNode!=NULL)
    {
        TempNode2=TempNode1;
        TempNode1=TempNode1->nextNode;
    }
    TempNode2->nextNode=NULL;
    printf("%d is deleted from the End\n ",TempNode1->data);
    free(TempNode1) ;  // delete the front node or Memory deallocation of front node.
}
int main()
{
    int choice=0;
    //Create 4 node statically and Initialize manually
    struct CreateNode* Node1=(struct CreateNode *)malloc(sizeof(struct CreateNode *)); 
    struct CreateNode* Node2=(struct CreateNode *)malloc(sizeof(struct CreateNode *)); 
    struct CreateNode* Node3=(struct CreateNode *)malloc(sizeof(struct CreateNode *)); 
    struct CreateNode* Node4=(struct CreateNode *)malloc(sizeof(struct CreateNode *)); 
    Node1->data=90;
    Node2->data=100;
    Node3->data=200;
    Node4->data=300;
    
    Node1->nextNode=Node2;
    Node2->nextNode=Node3;
    Node3->nextNode=Node4;
    Node4->nextNode=NULL;
    
    HeadPointer=Node1;  // HeadPointer pointing to the Node1
    
    printf("Node data before deletion process :\n");
    while(HeadPointer->nextNode!=NULL)
    {
        printf("%d ",HeadPointer->data);
        HeadPointer=HeadPointer->nextNode;
    }
    printf("%d ",HeadPointer->data);
    HeadPointer=Node1;
    while(choice==0)
    {
        printf("\nPress 0 for End deletion :");
        scanf("%d",&choice);
        if(choice==0)
        {
            deleteNodeAtEnd();
        }
        else
        {
            choice=1;
        }
    }
    
    printf("Node data after deletion process :\n");
    while(HeadPointer!=NULL)
    {
        printf("%d ",HeadPointer->data);
        HeadPointer=HeadPointer->nextNode;
    }

    return 0;
}

Time & Space Complexity

  • For reaching to the last node ,we have to traverse the all node ,then complexity will be O(n).
  • Space complexity will be O(1).

Leave a Reply

Your email address will not be published. Required fields are marked *