A circular linked list is a variation of the linked list data structure where the last node’s ‘next’ pointer points back to the first node, forming a loop. This python program demonstrates how to convert a singly linked list into a circular linked list.
Problem Statement
Given a singly linked list, your goal is to convert it into a circular linked list by making the last node’s ‘next’ pointer point back to the first node.
Python Program to Convert Singly Linked List to Circular List
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def convert_to_circular(self):
if not self.head:
return
current = self.head
while current.next:
current = current.next
current.next = self.head
def display(self):
if not self.head:
print("List is empty")
return
current = self.head
while True:
print(current.data, end=" -> ")
current = current.next
if current == self.head:
break
print("...")
# Input: Creating a linked list
linked_list = LinkedList()
elements = [1, 2, 3, 4, 5]
for element in elements:
linked_list.append(element)
print("Original Linked List:")
linked_list.display()
linked_list.convert_to_circular()
print("\nCircular Linked List:")
linked_list.display()
Input / Output
