For deleting the last node ,we have to traverse the whole list and reach the last node, at the last node ,we have to apply the deletion logic which is following :
- Take one Temp Variable and assign it by HeadPointer.
- Traverse the whole list using Temp.
- Refer the below Working Process :
Working Process
Code Implementation
#include <stdio.h>
#include<iostream>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#include<malloc.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 previuos element
};
struct CreateNode *HeadPointer = NULL; // Initialization of HeadPointer
void DeletetNodeAtEndDLL() // Method of End Deletion
{
struct CreateNode* Temp = HeadPointer;
while (Temp->nextNode!=NULL)
{
Temp = Temp->nextNode;
}
Temp->prevNode->nextNode= NULL;
std::cout << "\nDataElement " << Temp->data << " has been deleted at End\n";
}
int main()
{
int choice = 0;
//Create 5 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 *));
struct CreateNode* Node5 = (struct CreateNode *)malloc(sizeof(struct CreateNode *));
//Data Initialization
Node1->data = 90;
Node2->data = 100;
Node3->data = 200;
Node4->data = 300;
Node5->data = 400;
//Address Initialization
Node1->prevNode = NULL;
Node1->nextNode = Node2;
Node2->prevNode = Node1;
Node2->nextNode = Node3;
Node3->prevNode = Node2;
Node3->nextNode = Node4;
Node4->prevNode = Node3;
Node4->nextNode = Node5;
Node5->prevNode = Node4;
Node5->nextNode = NULL;
HeadPointer = Node1; // HeadPointer pointing to the Node1
printf("Node Before Deletion : ");
struct CreateNode* Temp = HeadPointer;
while (Temp->nextNode != NULL)
{
printf("%d ", Temp->data);
Temp = Temp->nextNode;
}
printf("%d ", Temp->data);
while (choice == 0)
{
printf("\nPress 0 for End deletion :");
std::cin >> choice;
if (choice == 0)
{
DeletetNodeAtEndDLL();
}
else
{
choice = 1; // dont delete the node
}
}
printf("\nNode data after Deletion process :\n");
Temp = HeadPointer;
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).