circular linked list using linked list in python
circular linked list in Python
Introduction
A circular linked list is a variation of a singly linked list where the last node points back to the first node instead of having a None
reference. This forms a circular structure, allowing for continuous traversal.
In this article, we will implement a circular linked list in Python using a linked list data structure.
# Circular linked list using linked list in Python
# Node structure
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to insert a new node at the beginning of the list
def push(head, data):
if not head:
return Node(data)
newNode = Node(data)
newNode.next = head
head = newNode
return head
# Function to convert singly linked list into circular linked list
def circular(head):
start = head
while head.next is not None:
head = head.next
head.next = start # Connecting last node to first node
return start
# Function to display elements of the circular linked list
def displayList(node):
start = node
while node.next is not start:
print("{} ".format(node.data), end="")
node = node.next
print("{} ".format(node.data), end="")
# Driver Code
if __name__ == '__main__':
# Initialize an empty list
head = None
head = push(head, 15)
head = push(head, 14)
head = push(head, 13)
head = push(head, 22)
head = push(head, 17)
# Convert the list into a circular linked list
circular(head)
print("Display List:")
displayList(head)
data
and next
pointer.Display List:
17 22 13 14 15
A circular linked list is a useful data structure in various real-world applications. Python makes it simple to implement using classes and pointers. This article covered creating, converting, and displaying a circular linked list.