เมื่อจำเป็นต้องค้นหาองค์ประกอบในรายการที่เชื่อมโยงแบบทวีคูณ จะต้องสร้างคลาส 'โหนด' ในคลาสนี้มีแอตทริบิวต์สามรายการ ได้แก่ ข้อมูลที่มีอยู่ในโหนด การเข้าถึงโหนดถัดไปของรายการที่เชื่อมโยง และการเข้าถึงโหนดก่อนหน้าของรายการที่เชื่อมโยง
ต้องสร้างคลาสอื่นที่จะมีฟังก์ชันเริ่มต้น และส่วนหัวของโหนดจะถูกเตรียมข้อมูลเบื้องต้นเป็น "ไม่มี" ภายในส่วนนี้
ผู้ใช้กำหนดวิธีการหลายวิธีในการเพิ่มโหนดในรายการที่เชื่อมโยง เพื่อแสดงโหนด และเพื่อค้นหาโหนดเฉพาะในรายการที่เชื่อมโยง
ในรายการที่เชื่อมโยงแบบทวีคูณ โหนดมีตัวชี้ โหนดปัจจุบันจะมีตัวชี้ไปยังโหนดถัดไปและโหนดก่อนหน้า ค่าสุดท้ายในรายการจะมีค่า 'NULL' ในพอยน์เตอร์ถัดไป สามารถเดินทางได้ทั้งสองทิศทาง
ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -
ตัวอย่าง
class Node:
def __init__(self, my_data):
self.previous = 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 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 search_node(self, val_to_search):
i = 1;
flag_val = False;
curr = self.head;
if(self.head == None):
print("List is empty")
return
while(curr != None):
if(curr.data == val_to_search):
flag_val = True
break
curr = curr.next
i = i + 1
if(flag_val):
print("The node is present in the list at position : ")
print(i)
else:
print("The node isn't present in the list")
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(24)
my_instance.add_data(0)
my_instance.print_it()
print("The element 77 is being searched... ")
my_instance.search_node(77)
print("The element 7 is being searched... ")
my_instance.search_node(7) ผลลัพธ์
Elements are being added to the doubly linked list The nodes in the doubly linked list are : 10 24 54 77 24 0 The element 77 is being searched... The node is present in the list at position : 4 The element 7 is being searched... The node isn't present in the list
คำอธิบาย
- สร้างคลาส 'โหนด' แล้ว
- สร้างคลาสอื่นที่มีคุณสมบัติที่จำเป็นแล้ว
- มีการกำหนดวิธีการอื่นที่ชื่อว่า 'add_data' ซึ่งใช้ในการเพิ่มข้อมูลไปยังรายการที่เชื่อมโยงแบบวงกลม
- มีการกำหนดวิธีการอื่นที่ชื่อว่า 'search_node' ซึ่งใช้พารามิเตอร์ที่ต้องค้นหาในรายการที่เชื่อมโยงแบบทวีคูณ
- ค้นหาองค์ประกอบและส่งคืนดัชนี
- มีการกำหนดวิธีการอื่นที่ชื่อว่า 'print_it' ซึ่งใช้ในการแสดงรายการข้อมูลที่เชื่อมโยงบนคอนโซล
- วัตถุของคลาส 'double_list' ถูกสร้างขึ้น และมีการเรียกใช้เมธอดเพื่อเพิ่มข้อมูล
- มีการเรียกเมธอด 'search_node'
- มันวนซ้ำผ่านโหนดในรายการที่เชื่อมโยง และให้ดัชนีขององค์ประกอบหากพบ
- แสดงบนคอนโซลโดยใช้วิธี "print_it"