Insertion of node at last(end) in SLL

End insertion of node requires some more operation to complete the insertion:

  • First we nee to traverse the whole node until we get node that address is NULL,Or in simple word ,traverse the whole node till the last node.
  • When Last node is comes then perform insert 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 insertNodeAtEnd(int data)   // Method of front Addition
{
    //Memory Initialization for NewNode
    struct CreateNode* NewNode=(struct CreateNode *)malloc(sizeof(struct CreateNode *));  
    struct CreateNode* TempNode=NULL;
    if(NewNode==NULL)
    {
        printf("Sorry...Memory is not Initialized for NewNode....");
    }
    else
    {
        NewNode->data=data;  //Initialization of data into NewNode
        if(HeadPointer==NULL) // checking for the first Node.
        {
            NewNode->nextNode=NULL;
            HeadPointer=NewNode;
            printf("NewNode has been added...\n"); 
        }
        else
        {
            TempNode=HeadPointer;      //TempNode Initialization by HeadPointer
            while(TempNode->nextNode!=NULL) // searching for the last node
            {
                TempNode=TempNode->nextNode;
            }
            //Node arrangement with last and NewNode
            TempNode->nextNode=NewNode;
            NewNode->nextNode=NULL;
            printf("NewNode has been added...\n"); 
        }
    } 
}
int main()
{
    int data;
    int choice;
    do
    {
        printf("Enter the data for insertion :");
        scanf("%d",&data);
        insertNodeAtEnd(data);
        printf("Press 0 for more insertion :");
        scanf("%d",&choice);
    }while(choice==0);
    
    printf("Node data after insertion process :\n");
    while(HeadPointer!=NULL)
    {
        printf("%d ",HeadPointer->data);
        HeadPointer=HeadPointer->nextNode;
    }
    return 0;
}

Time & Space Complexity

  • For the End Insertion ,we need to traverse the node from first to last,So 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 *