Location base deletion is similar to the Insertion of node at specific location.we will be follow the below procedure :
- First we have to declare an Temp Variable and also one flag.
- flag will go towards the position value.
- when we will reached at required position node,then we have to arrange the node. and delete the node of specific position.
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 DeleteNodeAtLocation(int Position) // Method of Random Addition
{
int flag = 1;
struct CreateNode* Temp = NULL; //Temp Node
Temp = HeadPointer;
while (flag < Position-1)
{
Temp = Temp->nextNode;
flag++;
}
Temp->nextNode = Temp->nextNode->nextNode;
std::cout <<"\nNode-"<< Position <<"has been Deleted " ;
}
int main()
{
int Position;
//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 Deletion : ");
while (HeadPointer->nextNode != NULL)
{
std::cout << HeadPointer->data << " ";
HeadPointer = HeadPointer->nextNode;
}
std::cout << HeadPointer->data << " ";
HeadPointer = Node1;
printf("\nEnter Position of Node for Deletion :");
std::cin>> Position;
DeleteNodeAtLocation(Position);
printf("\nNode data after Deletion 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).