ภาพรวม
เมื่อต้องการนับจำนวนครั้งที่เกิดขององค์ประกอบเฉพาะใน 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 print_it(self):
curr = self.head
while curr:
print(curr.data)
curr = curr.next
def count_val(self, key):
return self.count_helper_fun(self.head, key)
def count_helper_fun(self, curr, key):
if curr is None:
return 0
if curr.data == key:
return 1 + self.count_helper_fun(curr.next, key)
else:
return self.count_helper_fun(curr.next, key)
my_instance = my_linked_list()
my_list = [56, 43, 70, 67, 89, 91, 70, 23, 46, 70]
for elem in my_list:
my_instance.add_value(elem)
print("The linked list contains the below elements:")
my_instance.print_it()
key_val = int(input('Enter the data item: '))
count_val = my_instance.count_val(key_val)
print('{0} occurs {1} time(s) in the list.'.format(key_val, count_val))
ผลลัพธ์ตัวอย่าง
The linked list contains the below elements: 56 43 70 67 89 91 70 23 46 70 Enter the data item: 70 70 occurs 3 time(s) in the list.
คำอธิบาย
- สร้างคลาส
Node - สร้างคลาส
my_linked_listพร้อมแอตทริบิวต์ที่จำเป็น - เมธอด
__init__เริ่มต้นโหนดแรก (head) และโหนดสุดท้ายเป็นNone - เมธอด
add_valueเพิ่มข้อมูลเข้า Linked List - เมธอด
print_itวนลูปและแสดงองค์ประกอบ - เมธอด
count_valเรียกฟังก์ชันช่วยเหลือ - ฟังก์ชันช่วยเหลือ
count_helper_funหาความถี่ขององค์ประกอบเฉพาะใน Linked List - สร้างอ็อบเจกต์ของ
my_linked_list - เรียกเมธอด
count_valเพื่อหาความถี่ขององค์ประกอบเฉพาะ - แสดงผลลัพธ์บนคอนโซล