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

โปรแกรม Python แทรกโหนดใหม่หัว Circular Linked List


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

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

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

กำหนดเมธอดโดยผู้ใช้สำหรับเพิ่มโหนดหน้าลิสต์ และพิมพ์ค่าโหนด

ตัวอย่าง

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

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

    def add_at_beginning(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:
            temp = self.head
            new_node.next = temp
            self.head = new_node
            self.tail.next = self.head

    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_linked_list:
    my_cl = list_creation()
    print("Values are being added to the list")
    my_cl.add_at_beginning(21)
    my_cl.print_it()
    my_cl.add_at_beginning(53)
    my_cl.print_it()
    my_cl.add_at_beginning(76)
    my_cl.print_it()

ผลลัพธ์

Values are being added to the list
21
53 21
76 53 21

คำอธิบาย

  • สร้างคลาส 'Node'
  • สร้างคลาสอื่นพร้อมแอตทริบิวต์ที่จำเป็น
  • กำหนดเมธอด 'add_at_beginning' สำหรับเพิ่มข้อมูลหน้า Circular Linked List ก่อนโหนด 'head'
  • กำหนดเมธอด 'print_it' สำหรับแสดงโหนด
  • สร้างออบเจ็กต์ของคลาส 'list_creation' และเรียกใช้เมธอด
  • เมธอด 'init' กำหนดโหนดแรกและสุดท้ายเป็น None
  • เรียกใช้เมธอด 'add_at_beginning'
  • เมธอดจะหาหัวลิสต์ เพิ่มองค์ประกอบก่อนหน้า และอ้างอิงที่อยู่ไปยัง tail pointer และ next pointer
  • แสดงผลด้วยเมธอด 'print_it'