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 def add_at_beginning(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: temp = self.head; new_node.next = temp; self.head = new_node; self.tail.next = self.head; 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("Values are being added to the list") my_cl.add_at_beginning(21); my_cl.print_it(); my_cl.add_at_beginning(53); my_cl.print_it(); my_cl.add_at_beginning(76); my_cl.print_it();
輸出
Values are being added to the list 21 53 21 76 53 21
解釋
- 建立“Node”類。
- 建立另一個具有所需屬性的類。
- 定義另一個名為“add_at_beginning”的方法,用於在開頭(即“head”節點之前)將資料新增到迴圈連結串列。
- 定義另一個名為“print_it”的方法,用於顯示迴圈連結串列的節點。
- 建立“list_creation”類的物件,並在其上呼叫方法以新增資料。
- 定義一個“init”方法,將迴圈連結串列的第一個和最後一個節點設定為None。
- 呼叫“add_at_beginning”方法。
- 它獲取連結串列的頭,在它之前新增一個元素,並將它的地址引用到尾指標和下一個指標。
- 使用“print_it”方法在控制檯上顯示。
廣告