Python程式:在迴圈連結串列中間插入新節點


需要在迴圈連結串列中間插入一個新節點時,需要建立一個名為“節點(Node)”的類。在這個類中,有兩個屬性:節點中存在的資料以及對連結串列中下一個節點的訪問。

在迴圈連結串列中,表頭和表尾彼此相鄰。它們連線成一個環,最後一個節點沒有“NULL”值。

需要建立另一個類,該類將具有一個初始化函式,並且節點的頭將初始化為“None”。

使用者定義了多個方法來在連結串列中間新增節點以及列印節點值。

下面是對此的演示:

示例

線上演示

class Node:  
   def __init__(self,data):  
      self.data = data
      self.next = None  
   
class list_creation:  
   def __init__(self):  
      self.head = Node(None)  
      self.tail = Node(None)  
      self.head.next = self.tail  
      self.tail.next = self.head  
      self.size = 0;  

   def add_data(self,my_data):  
      new_node = Node(my_data)
      if self.head.data is None:  
       self.head = new_node  
       self.tail = new_node  
       new_node.next = self.head  
      else:  
         self.tail.next = new_node
         self.tail = new_node
         self.tail.next = self.head
      self.size = self.size+1

   def add_in_between(self,my_data):  
      new_node = Node(my_data);  
      if(self.head == None):  
         self.head = new_node;  
         self.tail = new_node;  
         new_node.next = self.head;  
      else:  
         count = (self.size//2) if (self.size % 2 == 0) else ((self.size+1)//2);  
         temp = self.head;  
         for i in range(0,count):  
            curr = temp;  
            temp = temp.next;  
         curr.next = new_node;  
         new_node.next = temp;  
      self.size = self.size+1;
         
   def print_it(self):  
      curr = self.head;  
      if self.head is None:  
         print("The list is empty");  
         return;  
      else:
         print(curr.data)
         while(curr.next != self.head):  
            curr = curr.next;  
            print(curr.data)
         print("\n");  
   
class circular_linked_list:  
   my_cl = list_creation()
   print("Nodes are being added to the list")
   my_cl.add_data(21)
   my_cl.add_data(54)
   my_cl.add_data(78)
   my_cl.add_data(99)
   print("The list is :")
   my_cl.print_it();  
   my_cl.add_in_between(33);
   print("The updated list is :")
   my_cl.print_it();  
   my_cl.add_in_between(56);
   print("The updated list is :")
   my_cl.print_it();  
   my_cl.add_in_between(0);
   print("The updated list is :")
   my_cl.print_it();   

輸出

Nodes are being added to the list
The list is :
21
54
78
99

The updated list is :
21
54
33
78
99

The updated list is :
21
54
33
56
78
99

The updated list is :
21
54
33
0
56
78
99

解釋

  • 建立“節點(Node)”類。
  • 建立另一個具有所需屬性的類。
  • 定義另一個名為“add_in_between”的方法,用於在迴圈連結串列的中間(即中間位置)新增資料。
  • 定義另一個名為“print_it”的方法,用於顯示迴圈連結串列的節點。
  • 建立“list_creation”類的物件,並在其上呼叫方法以新增資料。
  • 定義一個“init”方法,將迴圈連結串列的第一個和最後一個節點設定為None。
  • 呼叫“add_in_between”方法。
  • 它遍歷列表,獲取中間索引並在該位置插入元素。
  • 使用“print_it”方法在控制檯上顯示此內容。

更新於:2021年3月13日

289 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告