เมื่อต้องการค้นหาค่าสูงสุดและต่ำสุดจากรายการที่เชื่อมโยงแบบทวีคูณ จะต้องสร้างคลาส 'โหนด' ในคลาสนี้มีแอตทริบิวต์สามรายการ ได้แก่ ข้อมูลที่มีอยู่ในโหนด การเข้าถึงโหนดถัดไปของรายการที่เชื่อมโยง และการเข้าถึงโหนดก่อนหน้าของรายการที่เชื่อมโยง
ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -
ตัวอย่าง
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' ที่โหนดรูท ส่วนหัว และส่วนท้ายของรายการที่เชื่อมโยงแบบทวีคูณเป็นไม่มี
- รายการมีการวนซ้ำ และพบค่าสูงสุดและต่ำสุด
- แสดงบนคอนโซลโดยใช้วิธี "print_it"