将给定的单链表转换为循环表的 Python 程序

当需要将单向链表转换为循环链表时,定义了一个名为'convert_to_circular_list'的方法,以确保最后一个元素指向第一个元素,从而使其本质上是循环的。

以下是相同的演示 -

示例

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):
      ifself.last_nodeis 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
      iflast.nextis 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)
输出结果
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...

解释

  • 创建了“节点”类。

  • 创建了另一个具有必需属性的“LinkedList_struct”类。

  • 它有一个“init”函数,用于初始化第一个元素,i.e“head”为“None”,最后一个节点为“None”。

  • 定义了另一个名为“add_elements”的方法,用于获取链表中的前一个节点。

  • 另一种名为“convert_to_circular_list”的方法被定义为将最后一个节点指向第一个节点,使其本质上是循环的。

  • 定义了一个名为“last_node_points”的方法,它检查列表是否为空,或者最后一个节点是否指向“无”,或者它指向链表的特定节点。

  • 创建了“LinkedList_struct”类的对象。

  • 用户输入用于链表中的元素。

  • 元素被添加到链表中。

  • 'last_node_points' 方法在这个链表上被调用。

  • 相关输出显示在控制台上。

猜你喜欢