Python Program to Convert Singly Linked List to Circular List

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

Python Program to Convert Singly Linked List to Circular List

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...