In Circular Singly Linked List(CSLL), 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<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 SearchingOfDataElementInCSLL(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 != HeadPointer)
{
if (TempNode->data == DataElement)
{
printf("%d Data element is present in Circular Single Linked List :", TempNode->data);
flag = 1;
break;
}
TempNode = TempNode->nextNode;
}
if (TempNode->nextNode == HeadPointer && 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 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 *));
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("Data Element before Searching : ");
struct CreateNode* Temp = HeadPointer;
while (Temp->nextNode != HeadPointer)
{
printf("%d ", Temp->data);
Temp = Temp->nextNode;
}
printf("%d ", Temp->data);
printf("\nEnter the Data Element for Searching :");
std::cin >> DataElement;
SearchingOfDataElementInCSLL(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).