Python程式刪除迴圈連結串列中間節點
當需要從迴圈連結串列中間刪除節點時,需要建立一個“節點”類。在這個類中,有兩個屬性,節點中存在的資料,以及對連結串列中下一個節點的訪問。
在迴圈連結串列中,頭部和尾部彼此相鄰。它們連線形成一個圓圈,並且在最後一個節點中沒有“NULL”值。
需要建立另一個類,該類將具有初始化函式,並且節點的頭部將初始化為“None”。size變數初始化為0。
將有一些使用者定義的函式,這些函式有助於將節點新增到連結串列中,在控制檯上列印它們,以及從中間索引刪除節點。
以下是相同內容的演示 -
示例
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 = int(self.size)+1;
def delete_from_mid(self):
if(self.head == None):
return;
else:
count = (self.size//2) if (self.size % 2 == 0) else ((self.size+1)//2);
if( self.head != self.tail ):
temp = self.head;
curr = None;
for i in range(0, count-1):
curr = temp;
temp = temp.next;
if(curr != None):
curr.next = temp.next;
temp = None;
else:
self.head = self.tail = temp.next;
self.tail.next = self.head;
temp = None;
else:
self.head = self.tail = None;
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()
my_cl.add_data(11)
my_cl.add_data(52)
my_cl.add_data(36)
my_cl.add_data(74)
print("The original list is :")
my_cl.print_it()
while(my_cl.head != None):
my_cl.delete_from_mid()
print("The list after updation is :")
my_cl.print_it();輸出
The original list is : 11 52 36 74 The list after updation is : 11 36 74 The list after updation is : 11 74 The list after updation is : 74 The list after updation is : The list is empty
解釋
- 建立“節點”類。
- 建立另一個具有所需屬性的類。
- 定義另一個名為“add_data”的方法,用於將資料新增到迴圈連結串列中。
- 定義另一個名為“delete_from_middle”的方法,該方法透過刪除其引用來逐個刪除中間的元素。
- 定義另一個名為“print_it”的方法,用於在控制檯上顯示連結串列資料。
- 建立“list_creation”類的物件,並在其上呼叫方法以新增資料。
- 呼叫“delete_from_middle”方法。
- 它遍歷連結串列中的節點,獲取中間索引並開始刪除元素。
- 使用“print_it”方法在控制檯上顯示此內容。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP