Front Insertion of node is very easy in Doubly Singly Linked List(DLL). we have to apply some basic node arrangement.
- First we need one new node for inserting, So allocate the memory for new node.
- and then insert the new node at beginning of DLL.
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* prevNode; //for storing the address of Previous element
};
struct CreateNode *HeadPointer = NULL; // Initialization of HeadPointer
void insertNodeAtFrontInDLL(int data) // Method of front Addition
{
//Memory Initialization for NewNode
struct CreateNode* NewNode = (struct CreateNode *)malloc(sizeof(struct CreateNode *));
if (NewNode != NULL)
{
if (HeadPointer == NULL)
{
NewNode->data = data;
HeadPointer = NewNode;
NewNode->nextNode = NULL;
NewNode->prevNode = NULL;
printf("NewNode has been added...\n");
}
else
{
NewNode->data = data;
HeadPointer->prevNode = NewNode;
NewNode->nextNode = HeadPointer;
NewNode->prevNode = NULL;
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 :");
std::cin >> data;
insertNodeAtFrontInDLL(data);
printf("Press 0 for more insertion :");
std::cin >> choice;
} while (choice == 0);
struct CreateNode* Temp = HeadPointer;
printf("Node data after insertion process :\n");
while (Temp->nextNode != NULL)
{
printf("%d ", Temp->data);
Temp = Temp->nextNode;
}
printf("%d ", Temp->data);
_getch();
return 0;
}
Time & Space Complexity
- Time Complexity will be O(1).
- Space Complexity will be O(1).