ภาพรวม
เมื่อต้องการหาความยาวของ Linked List ด้วย Recursion จะนิยามเมธอดเพิ่มองค์ประกอบ และเมธอดคำนวณความยาว นิยามฟังก์ชันช่วยเหลือ (helper) เรียกผ่านเมธอดคำนวณความยาวที่นิยามไว้
ตัวอย่างโค้ด
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):
return self.length_helper_fun(self.head)
def length_helper_fun(self, curr):
if curr is None:
return 0
return 1 + self.length_helper_fun(curr.next)
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 12 45 32 67 88 0 99 The length of the linked list is 7
คำอธิบาย
- สร้างคลาส
Node - สร้างคลาส
my_linked_listพร้อมแอตทริบิวต์ที่จำเป็น - เมธอด
__init__เริ่มต้นโหนดแรก (head) และโหนดสุดท้ายเป็นNone - เมธอด
add_valueเพิ่มข้อมูลเข้า Linked List - เมธอด
calculate_lengthเรียกฟังก์ชันช่วยเหลือหาความยาว - นิยามฟังก์ชันช่วยเหลือ เนื่องจากต้องใช้ Recursion
- ตรวจสอบค่าปัจจุบันของโหนด และคืนค่าความยาว
- สร้างอ็อบเจกต์ของ
my_linked_list - รับ input จากผู้ใช้สำหรับองค์ประกอบใน Linked List
- เรียกเมธอดเพื่อเพิ่มข้อมูล
- เรียกเมธอด
calculate_lengthและแสดงผลบนคอนโซล