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):
      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)

輸出

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...

解釋

  • 建立“Node”類。

  • 建立另一個具有所需屬性的“LinkedList_struct”類。

  • 它有一個“init”函式,用於初始化第一個元素,即“head”為“None”和最後一個節點為“None”。

  • 定義了另一個名為“add_elements”的方法,用於獲取連結串列中的前一個節點。

  • 定義了另一個名為“convert_to_circular_list”的方法,該方法將最後一個節點指向第一個節點,使其具有迴圈特性。

  • 定義了一個名為“last_node_points”的方法,該方法檢查列表是否為空,或者最後一個節點是否指向“None”,或者它是否指向連結串列的特定節點。

  • 建立“LinkedList_struct”類的物件。

  • 獲取使用者輸入的連結串列元素。

  • 將元素新增到連結串列中。

  • 在此連結串列上呼叫“last_node_points”方法。

  • 在控制檯上顯示相關的輸出。

更新於: 2021年4月15日

298 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.