使用递归反转堆栈的 Python 程序
pythonserver side programmingprogramming
当需要使用递归反转堆栈数据结构时,除了定义添加值、删除值和打印堆栈元素的方法外,还定义了 ‘stack_reverse’ 方法。
下面是相同的演示 −
示例
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
解释
创建‘Stack_structure’类,用于初始化一个空列表。
定义‘check_empty’方法来查看堆栈是否为空。
定义另一个名为‘push_val’的方法,用于将元素添加到堆栈。
定义另一个名为‘pop_val’的方法,用于从堆栈中删除元素。
定义一个名为‘print_it’的方法,用于打印堆栈的元素。
定义一个名为‘insert_bottom’的方法定义,将元素添加到堆栈底部,而不是默认添加到顶部。
定义了另一个名为‘stack_reverse’的方法,它有助于反转给定的堆栈。
定义了此‘Stack_structure’的一个实例。
堆栈的元素取自用户。
它被迭代,并调用方法将值添加到堆栈并将其打印在控制台上。
现在,在此列表上调用‘stack_reverse’。
调用‘print_it’以在控制台上显示反转的堆栈。