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

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


ภาพรวม

เมื่อต้องการแสดงโหนดสลับใน 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 alternate_nodes(self):
        self.alternate_helper_fun(self.head)

    def alternate_helper_fun(self, curr):
        if curr is None:
            return
        print(curr.data, end=' ')
        if curr.next:
            self.alternate_helper_fun(curr.next.next)

my_instance = my_linked_list()
my_list = input("Enter the elements of the linked list :").split()
for elem in my_list:
    my_instance.add_value(elem)
print("The alternate elements in the linked list are :")
my_instance.alternate_nodes()

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

Enter the elements of the linked list :78 56 34 52 71 96 0 80
The alternate elements in the linked list are : 78 34 71 0

คำอธิบาย

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