Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python แสดงโหนดทั้งหมดใน Linked List ด้วย Recursion


ภาพรวม

เมื่อต้องการแสดงองค์ประกอบ/โหนดใน Linked List โดยใช้ Recursion จะนิยามเมธอดเพิ่มค่า และเมธอดแสดงองค์ประกอบ มีเมธอดช่วยเหลือ (helper) ใช้ Recursion เรียกฟังก์ชันช่วยเหลือซ้ำๆ เพื่อแสดงค่า

ตัวอย่างโค้ด

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):
        self.helper_print(self.head)

    def helper_print(self, curr):
        if curr is None:
            return
        print(curr.data)
        self.helper_print(curr.next)

my_instance = my_linked_list()
n = int(input('How many elements you wish to add ? '))
for i in range(n):
    data = int(input('Enter a data item : '))
    my_instance.add_value(data)
print('The linked list: ')
my_instance.print_it()

ผลลัพธ์ตัวอย่าง

How many elements you wish to add ? 4
Enter a data item : 34
Enter a data item : 67
Enter a data item : 12
Enter a data item : 89
The linked list: 34 67 12 89

คำอธิบาย

  • สร้างคลาส Node
  • สร้างคลาส my_linked_list พร้อมแอตทริบิวต์ที่จำเป็น
  • เมธอด __init__ เริ่มต้นโหนดแรก (head) และโหนดสุดท้ายเป็น None
  • เมธอด add_value เพิ่มข้อมูลเข้า Linked List
  • เมธอด print_it เรียกเมธอดช่วยเหลือแสดงข้อมูล Linked List
  • เมธอด helper_print แสดงข้อมูล Linked List บนคอนโซล
  • นิยามฟังก์ชันช่วยเหลือ เนื่องจากต้องใช้ Recursion
  • สร้างอ็อบเจกต์ของ my_linked_list
  • รับ input จำนวนองค์ประกอบใน Linked List
  • วนลูปช่วงนั้น เรียกเมธอดเพื่อเพิ่มข้อมูล
  • แสดงบนคอนโซลด้วยเมธอด print_it