How to Convert singly linked list into circular linked list in Python

In this tutorial, we shall convert a singly linked list into circular linked list in Python. A Linked List is a linear data structure where the elements are linked using pointers. A circular Linked List is obtained from a singly linked list as follows.

Algorithm

  1. Enter Elements into an empty linked list using the push function.
  2. To convert a linked list into a circular linked list, traverse through the linked list to find the last node.
  3. Last Node is the node that has NULL as its next node.
  4. Make the last node point to the starting node (last.next=start)
  5. Display the circular linked list.

Python program to convert the singly linked list into circular linked list

Below is our Python code:

class Node: 
  def __init__(self,data): 
    self.data = data 
    self.next = None

def push(head, data): 
  if not head: 
    return Node(data) 

  # Assign the data into newNode. 
  newNode = Node(data)  
  newNode.next = head 
  head = newNode 
  return head 
 
def circular(head): 
  start = head  
  while(head.next is not None): 
    head = head.next #to reach end of the list
   
  head.next = start #Link the end of linked list to start
  return start 
 
def displayList(node): 
  start = node 
  while(node.next is not start): 
    print("{} ".format(node.data),end="") 
    node=node.next

  # Display the last node of circular linked list. 
  print("{} ".format(node.data),end="") 

# Driver Code 
if __name__=='__main__': 
  
  # Start with empty list 
  head = None

  # Linked List 12 23 34 41 69 
  head = push(head, 69) 
  head = push(head, 41) 
  head = push(head, 34) 
  head = push(head, 23) 
  head = push(head, 12) 

  circular(head) 
  print("Display List:") 
  displayList(head)

After running the above program we can see the output result:

Display List:
12 23 34 41 69

Also Read Related topics to Linked Lists:

Thank You for reading and Keep Learning 🙂

Leave a Reply

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