Python程式建立包含n個節點的雙向連結串列並統計節點數量
當需要統計雙向連結串列中節點數量時,需要建立一個名為“Node”的類。在這個類中,有三個屬性:節點中存在的資料、訪問連結串列中下一個節點的許可權以及訪問連結串列中上一個節點的許可權。
在雙向連結串列中,節點具有指標。當前節點將擁有指向下一個節點和上一個節點的指標。列表中的最後一個值將在下一個指標中具有“NULL”值。它可以雙向遍歷。
以下是相同內容的演示 -
示例
class Node: def __init__(self, my_data): self.prev = None self.data = my_data self.next = None class count_val: def __init__(self): self.head = None self.tail = None 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; def count_node(self): my_counter = 0; curr = self.head; while(curr != None): my_counter = my_counter + 1; curr = curr.next; return my_counter; def print_it(self): curr = self.head if (self.head == None): print("The list is empty") return print("The nodes are :") while curr != None: print(curr.data) curr = curr.next my_instance = count_val() print("Elements are being added to the list") my_instance.add_data(10) my_instance.add_data(14) my_instance.add_data(24) my_instance.add_data(17) my_instance.add_data(22) my_instance.print_it() print("The nodes in the doubly linked list are : ") print(my_instance.count_node())
輸出
Elements are being added to the list The nodes are : 10 14 24 17 22 The nodes in the doubly linked list are : 5
解釋
- 建立“Node”類。
- 建立另一個具有所需屬性的類。
- 定義了一個名為“add_data”的方法,用於將資料新增到雙向連結串列中。
- 定義了另一個名為“count_node”的方法,該方法有助於獲取雙向連結串列中節點的數量。
- 定義了另一個名為“print_it”的方法,該方法顯示迴圈連結串列的節點。
- 建立“count_val”類的物件,並在其上呼叫方法以將雙向連結串列轉換為三叉樹。
- 定義了一個“init”方法,將雙向連結串列的根、頭和尾節點設定為None。
- 呼叫“count_node”方法。
- 它遍歷雙向連結串列,並獲取列表中的節點數量。
- 使用“print_it”方法在控制檯上顯示此資訊。
廣告