5 Best Ways to Create and Display a Circular Linked List in Python

Rate this post

πŸ’‘ Problem Formulation: A circular linked list is a sequential list of nodes where each node points to the next, and the last node points back to the first, creating a full circle. This article aims to provide Python programmers with various methods to create and visualize such a data structure. The goal is to transform a given collection of elements into a circular linked list and then display the nodes in a manner that clearly demonstrates the cyclical nature of the structure.

Method 1: Using Class and Node Structure

This method involves creating a Node class to represent each element and a CircularLinkedList class to manage the nodes. Both classes work together to establish a circular linked list wherein the last node’s next pointer will reference the first node, enforcing the circular nature of the list.

Here’s an example:

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)
            current = self.head
            while current.next != self.head:
                current = current.next
            current.next = new_node
            new_node.next = self.head

    def display(self):
        nodes = []
        current = self.head
        while current:
            nodes.append(str(current.data))
            current = current.next
            if current == self.head:
                break
        print(" -> ".join(nodes))

cllist = CircularLinkedList()
cllist.append(1)
cllist.append(2)
cllist.append(3)
cllist.display()    

Output:

1 -> 2 -> 3

This snippet defines two classes Node and CircularLinkedList. Node instances store individual data elements and a reference to the next node. The CircularLinkedList class contains methods to add nodes (append) and display the list (display). The display method ensures the circular nature by stopping when it reaches the head again.

Method 2: Simplified Class with Insertion Function

Method 3: Using Collections.deque

Method 4: Implementing Circular Linked List with a While True Loop

Bonus One-Liner Method 5: Utilizing Generator to Simulate a Circular Linked List

Summary/Discussion

Each of the methods presented offers a different approach to creating and displaying a circular linked list in Python. Here’s a quick summary:

  • Method 1: Class and Node Structure. This method uses traditional object-oriented programming concepts, providing clear structures and easy maintainability. However, it may be more verbose than necessary for simple applications.
  • Method 2: Simplified Class. By streamlining the class structure, this approach offers a more concise but equally effective solution. Its simplicity makes it less flexible for extended functionalities.
  • Method 3: Using Collections.deque. This method leverages Python’s built-in collections module to create a circular-like behavior with natural performance benefits and less code, although it technically isn’t a pure circular linked list.
  • Method 4: While True Loop. A very straightforward technique that reduces the need for complex structures. However, without proper control structures, it can lead to infinite loops and other errors.
  • Method 5: Generator. This one-liner is the epitome of Python’s succinctness, ideal for small, quick tasks. It might be challenging for beginners and is not a full representation of a linked list’s functionality.