The Wayback Machine - https://web.archive.org/web/20240927015145/https://www.geeksforgeeks.org/python-program-to-search-an-element-in-a-circular-linked-list/
Open In App

Python program to Search an Element in a Circular Linked List

Last Updated : 18 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
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, the task is to check if key is present in the linked list or not. Examples: Input: 14 -> 21 -> 11 -> 30 -> 10, key = 14Output: YesExplanation: 14 is present in the linked list. Input: 6 -> 21 -> 17 -> 30 -> 10 -> 8, key = 13Output: NoExplanation: No node in the linked list has value = 13. Ta
13 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
Python Program for Anagram Substring Search (Or Search for all permutations)
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n > m. Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found a
4 min read
Python Program For Searching An Element In A Linked List
Write a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise. bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then function should return false. If key to be searched is 1
4 min read
Python Program For Moving Last Element To Front Of A Given Linked List
Write a function that moves the last element to the front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4. Algorithm: Traverse the list till the last node. Use two pointers: one to store the address of the last node and the other
3 min read
Python Program For Moving All Occurrences Of An Element To End In A Linked List
Given a linked list and a key in it, the task is to move all occurrences of the given key to the end of the linked list, keeping the order of all other elements the same. Examples: Input : 1 -> 2 -> 2 -> 4 -> 3 key = 2 Output : 1 -> 4 -> 3 -> 2 -> 2 Input : 6 -> 6 -> 7 -> 6 -> 3 -> 10 key = 6 Output : 7 ->
6 min read
Python Program For Finding The Middle Element Of A Given Linked List
Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the outpu
4 min read
Remove all occurrences of one Linked list in another Linked list
Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 -> 5. Input: head1 = 3 -> 6 -> 9 -> 8 -
9 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7< – > 6 < – > 8 < – > 11 < – > 3, K = 3 Output: 8 < – > 6 < – > 7 < – > 3 < – > 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 < – > 6
13 min read
XOR Linked List: Remove last node of the Linked List
Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<–>7<–>9<–>7Output: 4<–>7<–>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<–>7<–>9 Input: 10Output: List is emptyExplanation: After deleting the only node present
15+ min read
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 <-> 7 <-> 9 <-> 7Output: 7 <-> 4 <-> 7 <-> 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are swapped to form the sequence {9, 7}. Input: 1 <
12 min read
Linked List of Linked List
Linked list of linke­d list, also known as nested linke­d lists, is a type of Linked List where each main node stores another full linked list. This structure­ beats old, plain linked lists. It gives way more­ flexibility to store and manage comple­x data. In this article we will learn about the basics of Linked List of Linked List, how to create L
9 min read
Check if most frequent element in Linked list is divisible by smallest element
Given a Linked list, the task is to check if the most frequently occurring element in the linked list is divisible by the smallest element in the linked list. If divisible then return true otherwise return false. Note: If there is more than one mode then take the greater mode. Examples: Input: Linked List: 4 -> 2 -> 1 -> 3 -> 3 -> 3O
7 min read
Python Program For Finding The Length Of Longest Palindrome List In A Linked List Using O(1) Extra Space
Given a linked list, find the length of the longest palindrome list that exists in that linked list. Examples: Input : List = 2->3->7->3->2->12->24 Output : 5 The longest palindrome list is 2->3->7->3->2 Input : List = 12->4->4->3->14 Output : 2 The longest palindrome list is 4->4 Recommended: Please sol
3 min read
Python program to search for the minimum element occurring consecutively n times in a matrix
Given a matrix containing n rows. Each row has an equal number of m elements. The task is to find elements that come consecutively n times horizontally, vertically, diagonally in the matrix. If there are multiple such elements then print the smallest element. If there is no such element then print -1.Examples: Input : n = 4 mat[5][5] 2 1 3 4 5 3 2
4 min read
Javascript Program For Finding The Middle Element Of A Given Linked List
Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the outpu
4 min read
Javascript Program For Searching An Element In A Linked List
Write a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise. bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then function should return false. If key to be searched is 1
3 min read
Python | Print list elements in circular range
Given a list of elements, the task is to print element in group of k till n-iteration in circular range. Examples: Input: list = [1, 2, 3, 4, 5, 6, 7], k = 3, n =10 Output: [1, 2, 3] [4, 5, 6] [7, 1, 2] [3, 4, 5] [6, 7, 1] [2, 3, 4] [5, 6, 7] [1, 2, 3] [4, 5, 6] [7, 1, 2] Input: list = [10, 20, 30, 40, 50, 60, 70], k = 4, n = 5 Output: [10, 20, 30,
3 min read
Python program to get the indices of each element of one list in another list
Given 2 lists, get all the indices of all occurrence of each element in list2 from list1. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 4] Output : [[3], [1, 9], [0, 7]] Explanation : 5 is present at 1st and 9th index. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 8] Output : [[3], [1, 9],
7 min read
Python3 Program to Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places. Examples: Input: list = 1->2->3->4->5->6, m = 2, n = 5, k = 2 Output: 1->4->5->2->3->6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
4 min read
Python3 Program for Search an element in a sorted and rotated array
An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time. Example: Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
8 min read
Python | Slicing list from Kth element to last element
Python list slicing slices the list from start index till end - 1, specified as list elements. So its tricky when we require to also slice the last element of list. Trying to slice till list size + 1 gives an error. Let's discuss ways in which last element can be included during a list slice. Method #1 : Using None During list slicing, giving the d
6 min read
Python | Insert Nth element to Kth element in other list
Sometimes, while working with Python list, there can be a problem in which we need to perform the inter-list shifts of elements. Having a solution to this problem is always very useful. Let’s discuss the certain way in which this task can be performed. Method 1: Using pop() + insert() + index() This particular task can be performed using a combinat
9 min read
Python3 Program for Maximum circular subarray sum
Given n numbers (both +ve and -ve), arranged in a circle, find the maximum sum of consecutive numbers. Examples: Input: a[] = {8, -8, 9, -9, 10, -11, 12}Output: 22 (12 + 8 - 8 + 9 - 9 + 10)Input: a[] = {10, -3, -4, 7, 6, 5, -4, -1} Output: 23 (7 + 6 + 5 - 4 -1 + 10) Input: a[] = {-1, 40, -14, 7, 6, 5, -4, -1}Output: 52 (7 + 6 + 5 - 4 - 1 - 1 + 40)M
5 min read
Python3 Program to Check if all rows of a matrix are circular rotations of each other
Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each other or not. Examples: Input: mat[][] = 1, 2, 3 3, 1, 2 2, 3, 1Output: Yes,All rows are rotated permutation of each other.Input: mat[3][3] = 1, 2, 3 3, 2, 1 1, 3, 2Output: No,As 3, 2, 1 is not a rotated or circular permutation of 1, 2, 3 The idea is bas
2 min read