Deletion at Ending(Last) in CSLL

For delete the last node in CSLL ,we need some extra effort to complete this task :

  • First we need some temporary variables to traverse the all node and reach at last node.
  • At last node we have to perform deletion operation.

Working Process

Code Implementation

#include <stdio.h>
#include<math.h>
#include<stdlib.h>
#include<iostream>
#include<conio.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 deleteNodeAtEndInCSLL()   // Method of End Deletion
{
	struct CreateNode* TempNode1 = NULL;  // Create one TempNode 
	struct CreateNode* TempNode2 = NULL;
	TempNode1 = HeadPointer;
	while (TempNode1->nextNode != HeadPointer)
	{
		TempNode2 = TempNode1;
		TempNode1 = TempNode1->nextNode;
	}
	TempNode2->nextNode = HeadPointer;
	printf("%d is deleted from the End\n ", TempNode1->data);
}
int main()
{
	int choice = 0;
	//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 *));
	struct CreateNode* Node5 = (struct CreateNode *)malloc(sizeof(struct CreateNode *));
	Node1->data = 90;
	Node2->data = 100;
	Node3->data = 200;
	Node4->data = 300;
	Node5->data = 400;

	Node1->nextNode = Node2;
	Node2->nextNode = Node3;
	Node3->nextNode = Node4;
	Node4->nextNode = Node5;
	Node5->nextNode = Node1;

	HeadPointer = Node1;  // HeadPointer pointing to the Node1

	printf("Node data before deletion process :\n");
	struct CreateNode* Temp = HeadPointer;
	while (Temp->nextNode != HeadPointer)
	{
		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)
		{
			deleteNodeAtEndInCSLL();
		}
		else
		{
			choice = 1;
		}
	}

	printf("Node data after deletion process :\n");
	Temp = HeadPointer;
	while (Temp->nextNode != HeadPointer)
	{
		printf("%d ", Temp->data);
		Temp = Temp->nextNode;
	}
	printf("%d ", Temp->data);
	_getch();
	return 0;
}

Time & Space Complexity

  • Time Complexity will be O(n) always.
  • Space Complexity will be O(1).

Leave a Reply

Your email address will not be published. Required fields are marked *