Searching of the Data in SLL

In Singly Linked List, 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>
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 SearchingOfDataElementInSLL(int DataElement)   // Method of Search Operation
{
    int flag=0;  // flag to check the unavilability of DataElement
    struct CreateNode* TempNode=NULL;  // Create one TempNode 
    TempNode=HeadPointer;
    while(TempNode->nextNode!=NULL)
    {
        if(TempNode->data==DataElement)
        {
            printf("%d Data element is present in Single 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;
    
    Node1->nextNode=Node2;
    Node2->nextNode=Node3;
    Node3->nextNode=Node4;
    Node4->nextNode=NULL;
    
    HeadPointer=Node1;  // HeadPointer pointing to the Node1
    printf("Data Element before Searching : ");
    while(HeadPointer->nextNode!=NULL)
    {
        printf("%d ",HeadPointer->data);
        HeadPointer=HeadPointer->nextNode;
    }
     printf("%d ",HeadPointer->data);
    HeadPointer=Node1;
    printf("\nEnter the Data Element for Searching :");
    scanf("%d",&DataElement);
    SearchingOfDataElementInSLL(DataElement);
    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 *