Python Program to Convert a given Singly Linked List to a Circular List

PythonServer Side ProgrammingProgramming

When it is required to convert a singly linked list into a circular linked list, a method named ‘convert_to_circular_list’ is defined that ensures that the last elements points to the first element, thereby making it circular in nature.

Below is a demonstration of the same −

Example

 Live Demo

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

class LinkedList_struct:
   def __init__(self):
      self.head = None
      self.last_node = None

   def add_elements(self, data):
      if self.last_node is None:
         self.head = Node(data)
         self.last_node = self.head
      else:
         self.last_node.next = Node(data)
         self.last_node = self.last_node.next

def convert_to_circular_list(my_list):
   if my_list.last_node:
      my_list.last_node.next = my_list.head

def last_node_points(my_list):
   last = my_list.last_node
      if last is None:
         print('The list is empty...')
         return
      if last.next is None:
         print('The last node points to None...')
      else:
         print('The last node points to element that has {}...'.format(last.next.data))

my_instance = LinkedList_struct()

my_input = input('Enter the elements of the linked list.. ').split()
for data in my_input:
   my_instance.add_elements(int(data))

last_node_points(my_instance)

print('The linked list is being converted to a circular linked list...')
convert_to_circular_list(my_instance)

last_node_points(my_instance)

Output

Enter the elements of the linked list.. 56 32 11 45 90 87
The last node points to None...
The linked list is being converted to a circular linked list...
The last node points to element that has 56...

Explanation

  • The ‘Node’ class is created.

  • Another ‘LinkedList_struct’ class with required attributes is created.

  • It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’ and last node to ‘None’.

  • Another method named ‘add_elements’ is defined, that is used to fetch the previous node in the linked list.

  • Another method named ‘convert_to_circular_list’ is defined that points the last node to the first node, making it circular in nature.

  • A method named ‘last_node_points’ is defined, that checks if the list is empty, or if last node points to ‘None’, or it points to a specific node of the linked list.

  • An object of the ‘LinkedList_struct’ class is created.

  • The user input is taken for the elements in the linked list.

  • The elements are added to the linked list.

  • The ‘last_node_points’ method is called on this linked list.

  • Relevant output is displayed on the console.

raja
Published on 15-Apr-2021 16:59:01
Advertisements