Insertion of node at beginning(front) in SLL

Front insertion of node is very simple implementation, we need only some easy arrangement of node.

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 insertNodeAtFront(int data)   // Method of front Addition
{
    //Memory Initialization for NewNode
    struct CreateNode* NewNode=(struct CreateNode *)malloc(sizeof(struct CreateNode *));  
    if(NewNode!=NULL)
    {
        NewNode->data=data;
        NewNode->nextNode=HeadPointer;
        HeadPointer=NewNode;
        printf("NewNode has been added...\n");   
    }
    else
    {
     printf("Memory is not Initialized for NewNode.");   
    }   
}
int main()
{
    int data,choice;
    do
    {
        printf("Enter the data for insertion :");
        scanf("%d",&data);
        insertNodeAtFront(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

  • In the case of front insertion complexity will be O(1).
  • Space complexity will be O(1) in average case.

Leave a Reply

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