Python程式:查詢雙向連結串列中的最大值和最小值節點
當需要查詢雙向連結串列中的最大值和最小值時,需要建立一個“節點”類。在這個類中,有三個屬性:節點中存在的資料,對連結串列中下一個節點的訪問,以及對連結串列中前一個節點的訪問。
下面是一個演示:
示例
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
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 min_node(self):
curr = self.head
if(self.head == None):
print("The list is empty")
return 0
else:
min = self.head.data
while(curr != None):
if(min > curr.data):
min = curr.data
curr = curr.next
return min
def max_node(self):
curr = self.head
if(self.head == None):
print("The list is empty")
return 0
else:
max = self.head.data
while(curr != None):
if(curr.data > max):
max = curr.data
curr = curr.next
return max
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
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()
print("The node with maximum value is : ")
print(my_instance.max_node())
print("The node with minimum value is : ")
print(my_instance.min_node())輸出
Elements are being added to the doubly linked list The nodes in the doubly linked list are : 10 24 54 77 92 The node with maximum value is : 92 The node with minimum value is : 10
解釋
- 建立了“節點”類。
- 建立了另一個具有所需屬性的類。
- 定義了一個名為“add_data”的方法,用於將資料新增到雙向連結串列。
- 定義了另一個名為“print_it”的方法,用於顯示迴圈連結串列的節點。
- 定義了另一個名為“max_node”的方法,用於搜尋雙向連結串列中的最大值。
- 定義了另一個名為“min_node”的方法,用於搜尋雙向連結串列中的最小值。
- 建立了“double_list”類的物件,並呼叫其方法來查詢雙向連結串列中節點的最小值和最大值。
- 定義了一個“init”方法,將雙向連結串列的根、頭和尾節點設定為None。
- 遍歷列表,找到最大值和最小值。
- 使用“print_it”方法在控制檯中顯示。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP