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

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


ภาพรวม

เมื่อต้องการแสดงโหนดสลับใน Linked List โดยไม่ใช้ Recursion จะนิยามเมธอดเพิ่มองค์ประกอบ แสดงองค์ประกอบ และเมธอดดึงค่าสลับของ Linked List

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

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):
        curr = self.head
        while curr:
            print(curr.data)
            if curr.next is not None:
                curr = curr.next.next
            else:
                break

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 :56 78 43 51 23 89 0 6
The alternate elements in the linked list are : 56 43 23 0

คำอธิบาย

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