Insertion of any node at any specific position, is something complex stuff,but we have to play with arrangement of node.
- First we have to create one Temp Variable and one flag.
- Traverse the node as per position value and update the flag as well as Temp.
- When we got the exact position ,so apply the node arrangement.
Working Process
Code Implementation
#include <stdio.h>
#include<iostream>
#include<conio.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 insertNodeAtLocation(int DataElement, int Position) // Method of Random Addition
{
int flag = 1;
struct CreateNode* NewNode = (struct CreateNode *)malloc(sizeof(struct CreateNode *));// For NewNode
struct CreateNode* Temp = NULL; //Temp Node
Temp = HeadPointer;
while (flag < Position)
{
Temp = Temp->nextNode;
flag++;
}
NewNode->data = DataElement;
NewNode->nextNode = Temp->nextNode;
Temp->nextNode = NewNode;
std::cout<<"DataElement " <<DataElement<<" has been inserted after Node-"<<Position;
}
int main()
{
int Position, DataElement;
//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 Before Insertion : ");
while (HeadPointer->nextNode!=NULL)
{
std::cout << HeadPointer->data << " ";
HeadPointer = HeadPointer->nextNode;
}
std::cout << HeadPointer->data << " ";
HeadPointer = Node1;
printf("\nEnter the DataElement and Position for insertion :");
std::cin >> DataElement >> Position;
insertNodeAtLocation(DataElement, Position);
printf("\nNode data after insertion process :\n");
while (HeadPointer != NULL)
{
printf("%d ", HeadPointer->data);
HeadPointer = HeadPointer->nextNode;
}
_getch();
return 0;
}
Time & Space Complexity
- Worst Case : Time Complexity will be O(n).
- Best Case : Time Complexity will be O(1).
- Average Case : Time Complexity will be O(n).
- Worst Case Space Complexity will be O(1).