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

โปรแกรม Python สร้าง Stack ด้วย Linked List


ภาพรวม

เมื่อต้องการสร้างโครงสร้างข้อมูล Stack โดยใช้ Linked List จะนิยามเมธอดเพิ่ม (push) และลบ (pop) องค์ประกอบ

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

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

class Stack_structure:
    def __init__(self):
        self.head = None

    def push_val(self, data):
        if self.head is None:
            self.head = Node(data)
        else:
            newNode = Node(data)
            newNode.next = self.head
            self.head = newNode

    def pop_val(self):
        if self.head is None:
            return None
        else:
            del_Val = self.head.data
            self.head = self.head.next
            return del_Val

my_instance = Stack_structure()
while True:
    print('push ')
    print('pop')
    print('quit')
    my_input = input('What action would you like to perform ? ').split()
    operation = my_input[0].strip().lower()
    if operation == 'push':
        my_instance.push_val(int(my_input[1]))
    elif operation == 'pop':
        del_Val = my_instance.pop_val()
        if del_Val is None:
            print('The stack is empty.')
        else:
            print('The deleted value is : ', int(del_Val))
    elif operation == 'quit':
        break

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

push  pop quit
What action would you like to perform ? push 56
push  pop quit
What action would you like to perform ? push 78
push  pop quit
What action would you like to perform ? push 90
push  pop quit
What action would you like to perform ? pop
The deleted value is : 90
push  pop quit
What action would you like to perform ? quit

คำอธิบาย

  • สร้างคลาส Node
  • สร้างคลาส Stack_structure พร้อมแอตทริบิวต์ที่จำเป็น
  • เมธอด __init__ เริ่มต้นโหนดแรก (head) เป็น None
  • เมธอด push_val เพิ่มค่าเข้า Stack
  • เมธอด pop_val ลบค่าจากยอด Stack และคืนค่าที่ลบ
  • สร้างอินสแตนซ์ของ Stack_structure
  • ให้ตัวเลือก 3 อย่าง: push, pop, quit
  • ตัวเลือก push เพิ่มค่าเข้า Stack
  • ตัวเลือก pop ลบองค์ประกอบบนสุดจาก Stack
  • ตัวเลือก quit ออกจากลูป
  • ตาม input/choice ของผู้ใช้ จะทำการดำเนินการตามลำดับ
  • แสดงผลลัพธ์บนคอนโซล