Python program to Search an Element in a Circular Linked List

Python program to Search an Element in a Circular Linked List

To search for an element in a circular linked list in Python, you first need to define the structure of a circular linked list and then implement the search functionality. A circular linked list is a linked list where all nodes are connected in a circle, with no null at the end.

Here's a simple implementation:

Define Node and CircularLinkedList Classes

class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None def append(self, data): if not self.head: self.head = Node(data) self.head.next = self.head else: new_node = Node(data) cur = self.head while cur.next != self.head: cur = cur.next cur.next = new_node new_node.next = self.head def print_list(self): cur = self.head while cur: print(cur.data, end=" ") cur = cur.next if cur == self.head: break print() 

Implement Search Function

 def search(self, key): cur = self.head while cur: if cur.data == key: return True cur = cur.next if cur == self.head: break return False 

Example Usage

# Create a Circular Linked List cllist = CircularLinkedList() # Append items cllist.append(1) cllist.append(2) cllist.append(3) cllist.append(4) # Search for an element element = 3 if cllist.search(element): print(f"Element {element} found in the list.") else: print(f"Element {element} not found in the list.") # Print the list cllist.print_list() 

How It Works

  • Append Function: Adds a new element to the end of the circular linked list.
  • Search Function: Iterates over the list to find the element. Since it's a circular linked list, the iteration stops when it reaches the head again.
  • Print Function: To visualize the elements in the list. It stops printing when it completes a full circle.

This implementation provides a basic structure for a circular linked list and the ability to search for an element within it. Remember, in a circular linked list, the last node always points back to the first node (head), creating a circular loop.


More Tags

floating-point kestrel-http-server jtextfield android-networking css-loader setuptools crystal-reports android-sdcard arrays sylius

More Programming Guides

Other Guides

More Programming Examples