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

โปรแกรม Python กลับลำดับ Stack ด้วย Recursion (Recursive Stack Reversal)

กลับลำดับ Stack โดยใช้ Recursion: นำสมาชิกบนสุดออก เรียกฟังก์ชันซ้ำจน Stack ว่าง แล้วนำสมาชิกที่นำออกไปใส่ที่ก้น Stack ทีละตัว

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

class Stack_structure:
    def __init__(self):
        self.items = []
    def check_empty(self):
        return self.items == []
    def push_val(self, data):
        self.items.append(data)
    def pop_val(self):
        return self.items.pop()
    def print_it(self):
        for data in reversed(self.items):
            print(data)

def insert_bottom(instance, data):
    if instance.check_empty():
        instance.push_val(data)
    else:
        deleted_elem = instance.pop_val()
        insert_bottom(instance, data)
        instance.push_val(deleted_elem)

def stack_reverse(instance):
    if not instance.check_empty():
        deleted_elem = instance.pop_val()
        stack_reverse(instance)
        insert_bottom(instance, deleted_elem)

my_instance = Stack_structure()
data_list = input('Enter the elements to add to the stack: ').split()
for data in data_list:
    my_instance.push_val(int(data))

print('The reversed stack is:')
my_instance.print_it()
stack_reverse(my_instance)
print('The stack is:')
my_instance.print_it()

ผลลัพธ์

Enter the elements to add to the stack: 23 56 73 81 8 9 0
The reversed stack is:
0
9
8
81
73
56
23
The stack is:
23
56
73
81
8
9
0

คำอธิบาย

  • insert_bottom: ใส่ข้อมูลที่ก้น Stack (pop ทั้งหมด ใส่ข้อมูลใหม่ push กลับ)
  • stack_reverse: pop ตัวบนสุด เรียกตัวเองซ้ำจนว่าง แล้ว insert_bottom ทีละตัว
  • ผลลัพธ์: Stack ถูกกลับลำดับ (Top กลายเป็น Bottom)