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
Below is the implementation of the above approach:
Java
public class search {
class Node {
int data;
Node next;
public Node( int data) { this .data = data; }
}
public Node head = null ;
public Node tempo = null ;
public void addNode( int data)
{
Node new1 = new Node(data);
if (head == null ) {
head = new1;
}
else {
tempo.next = new1;
}
tempo = new1;
tempo.next = head;
}
public void find( int key)
{
Node temp = head;
int f = 0 ;
if (head == null ) {
System.out.println( "List is empty" );
}
else {
do {
if (temp.data == key) {
System.out.println(
"element is present" );
f = 1 ;
break ;
}
temp = temp.next;
} while (temp != head);
if (f == 0 ) {
System.out.println(
"element is not present" );
}
}
}
public static void main(String[] args)
{
search s = new search();
s.addNode( 5 );
s.addNode( 4 );
s.addNode( 3 );
s.addNode( 2 );
s.find( 2 );
s.find( 6 );
}
}
|
Outputelement is present
element is not present
Time Complexity: O(N), where N is the length of the Circular linked list.
Space Complexity: O(1) because it is using constant space