Python程式:刪除雙向連結串列中間的新節點
當需要從雙向連結串列中間刪除節點時,需要建立一個“節點”類。在這個類中,有三個屬性:節點中存在的資料、對連結串列中下一個節點的訪問以及對連結串列中上一個節點的訪問。
需要建立另一個類,該類將具有初始化函式,並且節點的頭在其中初始化為“None”。
使用者定義了多個方法來向連結串列新增節點、顯示節點以及從雙向連結串列的末尾刪除節點。
在雙向連結串列中,節點具有指標。當前節點將指向下一個節點和上一個節點。列表中的最後一個值在下一個指標中將具有“NULL”值。它可以雙向遍歷。
下面是對此的演示 -
示例
class Node:
def __init__(self, my_data):
self.prev = 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;
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 delete_from_middle(self):
if(self.head == None):
return;
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;
if(curr == self.head):
self.head = curr.next
self.tail.next = None
elif(curr == self.tail):
self.tail = self.tail.prev;
else:
curr.prev.next = curr.next;
curr.next.prev = curr.prev;
current = None;
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)
my_instance.add_data(77)
my_instance.add_data(92)
my_instance.print_it()
while(my_instance.head != None):
my_instance.delete_from_middle();
print("The list after deleting the element from the middle is : ")
my_instance.print_it();輸出
Elements are being added to the doubly linked list The nodes in the doubly linked list are : 10 24 54 77 92 The list after deleting the element from the middle is : The nodes in the doubly linked list are : 24 54 77 92 The list after deleting the element from the middle is : The nodes in the doubly linked list are : 54 77 92 The list after deleting the element from the middle is : The nodes in the doubly linked list are : 77 92 The list after deleting the element from the middle is : The nodes in the doubly linked list are : 92 The list after deleting the element from the middle is : The list is empty
解釋
- 建立“節點”類。
- 建立另一個具有所需屬性的類。
- 定義了一個名為“add_data”的方法,用於向雙向連結串列新增資料。
- 定義了另一個名為“print_it”的方法,用於顯示迴圈連結串列的節點。
- 定義了另一個名為“delete_from_middle”的方法,用於從中間刪除節點,並將上一個節點設為迴圈連結串列中的當前節點。
- 建立“double_list”類的物件,並在其上呼叫方法以從雙向連結串列的開頭刪除節點。
- 定義了一個“init”方法,將雙向連結串列的根、頭和尾節點設定為None。
- 迭代列表,並刪除連結串列中間索引的每個節點,直到為空。
- 使用“print_it”方法在控制檯中顯示。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP