เมื่อจำเป็นต้องค้นหาความยาวของรายการที่เชื่อมโยงโดยไม่ใช้การเรียกซ้ำ วิธีการในการเพิ่มองค์ประกอบในรายการที่เชื่อมโยง และวิธีการคำนวณความยาวของรายการที่เชื่อมโยงจะถูกกำหนด
ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -
ตัวอย่าง
class Node:
def __init__(self, data):
self.data = data
self.next = None
class my_linked_list:
def __init__(self):
self.head = None
self.last_node = None
def add_value(self, my_data):
if self.last_node is None:
self.head = Node(my_data)
self.last_node = self.head
else:
self.last_node.next = Node(my_data)
self.last_node = self.last_node.next
def calculate_length(self):
curr = self.head
length_val = 0
while curr:
length_val = length_val + 1
curr = curr.next
return length_val
my_instance = my_linked_list()
my_data = input('Enter elements of the linked list ').split()
for elem in my_data:
my_instance.add_value(int(elem))
print('The length of the linked list is ' + str(my_instance.calculate_length())) ผลลัพธ์
Enter elements of the linked list 34 12 56 86 32 99 0 6 The length of the linked list is 8
คำอธิบาย
-
สร้างคลาส "โหนด" แล้ว
-
สร้างคลาส "my_linked_list" อีกคลาสที่มีแอตทริบิวต์ที่จำเป็นแล้ว
-
มีฟังก์ชัน 'init' ที่ใช้ในการเริ่มต้นองค์ประกอบแรก นั่นคือ 'head' เป็น 'None' และโหนดสุดท้ายเป็น 'None'
-
มีการกำหนดวิธีการอื่นที่ชื่อว่า 'add_value' ซึ่งใช้ในการเพิ่มข้อมูลไปยังรายการที่เชื่อมโยง
-
มีการกำหนดวิธีการอื่นที่ชื่อว่า 'calculate_length' ซึ่งใช้เพื่อค้นหาความยาวของรายการที่เชื่อมโยง
-
วัตถุของคลาส 'my_linked_list' ถูกสร้างขึ้น
-
ผู้ใช้ป้อนข้อมูลเพื่อรับองค์ประกอบในรายการที่เชื่อมโยง
-
มีการเรียกใช้เมธอดเพื่อเพิ่มข้อมูล
-
เรียกวิธีการคำนวณ_length เพื่อหาความยาวของรายการ
-
เอาต์พุตนี้จะแสดงบนคอนโซล