For Last or End Insertion of node in Doubly Singly Linked List(DLL) ,we need some more iterations of node. we have to apply basic below rules :
- First we need one new node for inserting, So allocate the memory for new node.
- Traverse the all nodes from first to last.
- and then insert the new node at the ending of DLL.
Working Process
Code Implementation
#include <stdio.h>
#include <iostream>
#include<malloc.h>
#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 insertNodeAtEndInDLL(int data) // Method of End Addition
{
//Memory Initialization for NewNode
struct CreateNode* NewNode = (struct CreateNode *)malloc(sizeof(struct CreateNode *));
struct CreateNode* Temp = HeadPointer;
if (NewNode != NULL)
{
if (HeadPointer == NULL)
{
NewNode->data = data;
HeadPointer = NewNode;
NewNode->nextNode = NULL;
NewNode->prevNode = NULL;
printf("NewNode has been added...\n");
}
else
{
while (Temp->nextNode!=NULL)
{
Temp = Temp->nextNode;
}
NewNode->data = data;
NewNode->nextNode = NULL;
Temp->nextNode = NewNode;
NewNode->prevNode = Temp;
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;
insertNodeAtEndInDLL(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(n)
- Space Complexity will be O(1).