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:
- Initialize a node pointer, temp = head.
- Initialize a counter f=0 (to check if the element is present in a linked list or not).
- If the head is null then the print list is empty.
- Else start traversing the Linked List and if element found in Linked List increment in f.
- If the counter is zero, then the print element is not found.
- Else print element is present.
Below is the implementation of the above approach:
Python3
class Node:
def __init__( self ,data):
self .data = data;
self . next = None ;
class CircularLinkedList:
def __init__( self ):
self .head = Node( None );
self .tail = Node( None );
self .head. next = self .tail;
self .tail. next = self .head;
def add( self ,data):
newNode = Node(data);
if self .head.data is None :
self .head = newNode;
self .tail = newNode;
newNode. next = self .head;
else :
self .tail. next = newNode;
self .tail = newNode;
self .tail. next = self .head;
def findNode( self ,element):
current = self .head;
i = 1 ;
f = 0 ;
if ( self .head = = None ):
print ( "Empty list" );
else :
while ( True ):
if (current.data = = element):
f + = 1 ;
break ;
current = current. next ;
i = i + 1 ;
if (current = = self .head):
break ;
if (f > 0 ):
print ( "element is present" );
else :
print ( "element is not present" );
if __name__ = = '__main__' :
circularLinkedList = CircularLinkedList();
circularLinkedList.add( 1 );
circularLinkedList.add( 2 );
circularLinkedList.add( 3 );
circularLinkedList.add( 4 );
circularLinkedList.add( 5 );
circularLinkedList.add( 6 );
circularLinkedList.findNode( 2 );
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!