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

โปรแกรม Python ลบโหนดท้าย Circular Linked List


เมื่อต้องการลบโหนดจากท้ายของ Circular Linked List ต้องสร้างคลาส 'Node' ที่มีแอตทริบิวต์สองอย่าง: ข้อมูลในโหนด และการเข้าถึงโหนดถัดไป

ใน Circular Linked List หัวและท้ายอยู่ติดกัน เชื่อมเป็นวงกลม ไม่มีค่า 'NULL' ในโหนดสุดท้าย

สร้างคลาส 'linked_list' มีฟังก์ชันเริ่มต้น และหัวโหนดเริ่มต้นเป็น 'None'

ตัวอย่าง

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class linked_list:
    def __init__(self):
        self.head = Node(None)
        self.tail = Node(None)
        self.head.next = self.tail
        self.tail.next = self.head

    def add_value(self, my_data):
        new_node = Node(my_data)
        if self.head.data is None:
            self.head = new_node
            self.tail = new_node
            new_node.next = self.head
        else:
            self.tail.next = new_node
            self.tail = new_node
            self.tail.next = self.head

    def delete_from_end(self):
        if self.head == None:
            return
        else:
            if self.head != self.tail:
                curr = self.head
                while curr.next != self.tail:
                    curr = curr.next
                self.tail = curr
                self.tail.next = self.head
            else:
                self.head = self.tail = None

    def print_it(self):
        curr = self.head
        if self.head is None:
            print("The list is empty")
            return
        else:
            print(curr.data)
            while curr.next != self.head:
                curr = curr.next
                print(curr.data)
            print("\n")

class circular_list:
    my_cl = linked_list()
    my_cl.add_value(11)
    my_cl.add_value(32)
    my_cl.add_value(43)
    my_cl.add_value(57)
    print("The original list is :")
    my_cl.print_it()
    while my_cl.head != None:
        my_cl.delete_from_end()
        print("The list after deletion is :")
        my_cl.print_it()

ผลลัพธ์

The original list is : 11 32 43 57
The list after deletion is : 11 32 43
The list after deletion is : 11 32
The list after deletion is : 11
The list after deletion is : The list is empty

คำอธิบาย

  • สร้างคลาส 'Node'
  • สร้างคลาส 'linked_list' พร้อมแอตทริบิวต์ที่จำเป็น
  • กำหนดเมธอด 'add_data' สำหรับเพิ่มข้อมูลใน Circular Linked List
  • กำหนดเมธอด 'delete_from_end' ลบองค์ประกอบทีละตัวจากท้ายโดยลบการอ้างอิง
  • กำหนดเมธอด 'print_it' แสดงข้อมูล Linked List บนคอนโซล
  • สร้างออบเจ็กต์ของคลาส 'linked_list' และเรียกใช้เมธอด
  • แสดงผลด้วยเมธอด 'print_it'