Open In App

Python program to Search an Element in a Circular Linked List

Last Updated : 18 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A linked list is a kind of linear data structure where each node has a data part and an address part which points to the next node. A circular linked list is a type of linked list where the last node points to the first one, making a circle of nodes.

Example:

Input: CList = 6->5->4->3->2, find = 3
Output: Element is present
 
Input: CList = 6->5->4->3->2, find = 1
Output: Element is not present

Search an Element in a Circular Linked List

For example, if the key to be searched is 30 and the linked list is 5->4->3->2, then the function should return false. If the key to be searched is 4, then the function should return true. 

Approach: 

  1. Initialize a node pointer, temp = head.
  2. Initialize a counter f=0 (to check if the element is present in a linked list or not).
  3. If the head is null then the print list is empty.
  4. Else start traversing the Linked List and if element found in Linked List increment in f.
  5. If the counter is zero, then the print element is not found.
  6. Else print element is present.

Below is the implementation of the above approach:

Python3




# Python program to Search an Element
# in a Circular Linked List
        
# Class to define node of the linked list    
class Node: 
    def __init__(self,data):    
        self.data = data;
        self.next = None;
          
class CircularLinkedList:
      
    # Declaring Circular Linked List
    def __init__(self):    
        self.head = Node(None);    
        self.tail = Node(None);    
        self.head.next = self.tail;    
        self.tail.next = self.head;    
          
      
    # Adds new nodes to the Circular Linked List
    def add(self,data):    
          
        # Declares a new node to be added
        newNode = Node(data); 
          
        # Checks if the Circular
        # Linked List is empty
        if self.head.data is None:
              
            # If list is empty then new node
            # will be the first node
            # to be added in the Circular Linked List
            self.head = newNode;
            self.tail = newNode;
            newNode.next = self.head;
          
        else:
            # If a node is already present then
            # tail of the last node will point to
            # new node
            self.tail.next = newNode;
              
            # New node will become new tail
            self.tail = newNode;
              
            # New Tail will point to the head
            self.tail.next = self.head;    
                  
    # Function to search the element in the 
    # Circular Linked List
    def findNode(self,element):
          
        # Pointing the head to start the search
        current = self.head;
        i = 1;
          
        # Declaring f = 0
        f = 0;    
        # Check if the list is empty or not    
        if(self.head == None):
            print("Empty list"); 
        else:
            while(True):     
                # Comparing the elements
                # of each node to the
                # element to be searched
                if(current.data ==  element): 
  
                    # If the element is present
                    # then incrementing f
                    f += 1;    
                    break;
                  
                # Jumping to next node
                current = current.next;    
                i = i + 1;    
                  
                # If we reach the head
                # again then element is not 
                # present in the list so 
                # we will break the loop
                if(current == self.head):    
                    break;    
              
            # Checking the value of f
            if(f > 0):    
                print("element is present");    
            else:    
                print("element is not present");    
                  
# Driver Code
if __name__ == '__main__':
      
    # Creating a Circular Linked List
    '''
    Circular Linked List we will be working on:
    1 -> 2 -> 3 -> 4 -> 5 -> 6
    '''
    circularLinkedList = CircularLinkedList();
      
    #Adding nodes to the list    
    circularLinkedList.add(1);
    circularLinkedList.add(2);
    circularLinkedList.add(3);
    circularLinkedList.add(4);
    circularLinkedList.add(5);
    circularLinkedList.add(6);
      
    # Searching for node 2 in the list    
    circularLinkedList.findNode(2);
      
    #Searching for node in the list    
    circularLinkedList.findNode(7);


Output:

element is present
element is not present

Time Complexity: O(N), where N is the length of the Circular linked list.



Previous Article
Next Article

Similar Reads

Search an Element in Doubly Circular Linked List
Pre-requisite: Convert an Array to a Circular Doubly Linked List, Doubly Circular Linked ListGiven a doubly circular linked list. The task is to find the position of an element in the list. Image Representation: Algorithm: Declare a temp pointer, and initialize it to the head of the list.Iterate the loop until temp reaches the start address (last n
13 min read
Program for all operations on Circular Linked List in C
In a Circular linked list, every element has a link to its next element in the sequence, and the last element has a link to the first element. A circular linked list is similar to the singly linked list except that the last node points to the first node. Below is the image to illustrate the same: 1. Insertion at the beginning: Insert a new node as
11 min read
Java Program to Delete a Node From the Beginning of the Circular Linked List
In this article, we will learn about deleting a node from the beginning of a circular linked list. Consider the linked list as shown below. Example: Input : 5->3->4->(head node) Output: 3->4->(head node) Two cases arrive while solving the problem, Case 1: List is empty If the list is empty we will simply return. Case 2: List is not e
3 min read
Java Program to Delete a Node From the Ending of the Circular Linked List
In this article, we will learn about deleting a node from the ending of a circular linked list. Consider the linked list as shown below: Example: Input : 5->3->4->(head node) Output: 5->3->(head node) We will first initialize the list and add some data into it with the addNode() method and then proceed according to the below approach
3 min read
Menu Driven Program to implement all the operations of Doubly Circular Linked List
Circular Doubly Linked List has properties of both Doubly Linked List and Circular Linked List in which two consecutive elements are linked or connected by previous and next pointer and the last node points to the first node by next pointer and also the first node points to the last node by the previous pointer. The program implements all the funct
15+ min read
Python Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Circular Linked List in Python
A Circular Linked List is a variation of the standard linked list. In a standard linked list, the last element points to null, indicating the end of the list. However, in a circular linked list, the last element points back to the first element, forming a loop. In this article, we will discuss the circular linked list in Python. Table of Content Wh
13 min read
Search an element in a Linked List (Iterative and Recursive)
Given a linked list and a key 'X' in, the task is to check if X is present in the linked list or not. Examples: Input: 14->21->11->30->10, X = 14Output: YesExplanation: 14 is present in the linked list. Input: 6->21->17->30->10->8, X = 13Output: No Using O(N) Extra Space. The Approach: In this approach we use vector where
15+ min read
Convert an Array to a Circular Doubly Linked List
Prerequisite: Doubly Linked list, Circular Linked List, Circular Doubly Linked ListGiven an array of N elements. The task is to write a program to convert the array into a circular doubly linked list. The idea is to start traversing the array and for every array element create a new list node and assign the prev and next pointers of this node accor
8 min read
Insertion at Specific Position in a Circular Doubly Linked List
Prerequisite: Insert Element Circular Doubly Linked List.Convert an Array to a Circular Doubly Linked List.Given the start pointer pointing to the start of a Circular Doubly Linked List, an element and a position. The task is to insert the element at the specified position in the given Circular Doubly Linked List. Recommended: Please try your appro
15+ min read