Python程式在雙向連結串列中間插入新節點
當需要在雙向連結串列中間插入一個新節點時,需要建立一個“Node”類。在這個類中,有三個屬性:節點中存在的資料、對連結串列中下一個節點的訪問以及對連結串列中前一個節點的訪問。
下面是對此的演示 -
示例
class Node: def __init__(self, my_data): self.previous = None self.data = my_data self.next = None class double_list: def __init__(self): self.head = None self.tail = None self.size = 0 def add_data(self, my_data): new_node = Node(my_data) if(self.head == None): self.head = self.tail = new_node self.head.previous = None self.tail.next = None else: self.tail.next = new_node new_node.previous = self.tail self.tail = new_node self.tail.next = None self.size = self.size + 1 def print_it(self): curr = self.head if (self.head == None): print("The list is empty") return print("The nodes in the doubly linked list are :") while curr != None: print(curr.data) curr = curr.next def add_data_in_middle(self, my_data): new_node = Node(my_data); if(self.head == None): self.head = self.tail = new_node; self.head.previous = None; self.tail.next = None; else: curr = self.head; mid = (self.size//2) if(self.size % 2 == 0) else ((self.size+1)//2); for i in range(1, mid): curr = curr.next; temp = curr.next; temp.previous = curr; curr.next = new_node; new_node.previous = curr; new_node.next = temp; temp.previous = new_node; self.size = self.size + 1; my_instance = double_list() print("Elements are being added to the doubly linked list") my_instance.add_data(10) my_instance.add_data(24) my_instance.add_data(54) print("Elements are added to the middle of the list") my_instance.add_data_in_middle(77) my_instance.print_it() my_instance.add_data_in_middle(92) my_instance.print_it()
輸出
Elements are being added to the doubly linked list Elements are added to the middle of the list The nodes in the doubly linked list are : 10 24 77 54 The nodes in the doubly linked list are : 10 24 92 77 54
解釋
- 建立“Node”類。
- 建立另一個具有所需屬性的類。
- 定義了一個名為“add_data_in_middle”的方法,用於在雙向連結串列的中間索引新增資料。
- 定義了一個名為“add_data”的方法,用於幫助將節點新增到雙向連結串列中。
- 定義了另一個名為“print_it”的方法,用於顯示迴圈連結串列的節點。
- 建立“double_list”類的物件,並在其上呼叫方法以將資料新增到雙向連結串列中。
- 呼叫“add_data_in_middle”以將資料新增到連結串列的中間索引。
- 定義了一個“init”方法,將雙向連結串列的根、頭和尾節點設定為None。
- 使用“print_it”方法在控制檯上顯示此內容。
廣告