Searching of Data in DLL

In Doubly Linked List(DLL), If we want to know the existence of an data element then we have to apply Search operation :

  • First we have to create one Temp variable,and assign the address of HeadPointer to it.
  • Now start traversing from starting to last node. and on every node ,we have to find the required data element.

Working Process

Code Implementation

#include <stdio.h>
#include<math.h>
#include<stdlib.h>
#include<iostream>
#include<malloc.h>
#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* prevNode;   //for storing the address of previous element
};
struct CreateNode *HeadPointer = NULL;    // Initialization of HeadPointer
void SearchingOfDataElementInDLL(int DataElement)   // Method of Search Operation
{
	int flag = 0;  // flag to check the unavilability of DataElement
	struct CreateNode* TempNode = HeadPointer;  // Create one TempNode 
	while (TempNode->nextNode != NULL)
	{
		if (TempNode->data == DataElement)
		{
			printf("%d Data element is present in Doubly Linked List :", TempNode->data);
			flag = 1;
			break;
		}
		TempNode = TempNode->nextNode;
	}
	if (TempNode->nextNode == NULL && TempNode->data == DataElement)
	{
		printf("%d Data element is present in Single Linked List :", TempNode->data);
		flag = 1;
	}
	if (flag == 0)
	{
		printf("Sorry : Required Data element is not available in Single Linked List..");
	}
}
int main()
{
	int DataElement;
	//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;
	//Address Initilization
	Node1->prevNode = NULL;
	Node1->nextNode = Node2;

	Node2->prevNode = Node1;
	Node2->nextNode = Node3;

	Node3->prevNode = Node2;
	Node3->nextNode = Node4;

	Node4->prevNode = Node3;
	Node4->nextNode = NULL;

	HeadPointer = Node1;  // HeadPointer pointing to the Node1
	printf("Data Element before Searching : ");
	struct CreateNode* Temp = HeadPointer;
	while (Temp->nextNode != NULL)
	{
		printf("%d ", Temp->data);
		Temp = Temp->nextNode;
	}
	printf("%d ", Temp->data);
	printf("\nEnter the Data Element for Searching :");
	std::cin >> DataElement;
	SearchingOfDataElementInDLL(DataElement);
	_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).
  • Space Complexity will be O(1).

Leave a Reply

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