使用一个队列实现堆栈的 Python 程序
pythonserver side programmingprogramming
当需要使用单个队列实现堆栈时,需要一个 ‘Stack_structure’ 类以及一个 Queue_structure 类。这些类中定义了相应的方法来分别从堆栈和队列中添加和删除值。
下面是相同的演示 −
示例
class Stack_structure: def __init__(self): self.q = Queue_structure() def check_empty(self): return self.q.check_empty() def push_val(self, data): self.q.enqueue_operation(data) def pop_val(self): for _ in range(self.q.size_calculate() - 1): dequeued = self.q.dequeue_operation() self.q.enqueue_operation(dequeued) return self.q.dequeue_operation() class Queue_structure: def __init__(self): self.items = [] self.size = 0 def check_empty(self): return self.items == [] def enqueue_operation(self, data): self.size += 1 self.items.append(data) def dequeue_operation(self): self.size -= 1 return self.items.pop(0) def size_calculate(self): return self.size my_instance = Stack_structure() print('Menu') print('push <value>') print('pop') print('quit') while True: my_input = input('What operation 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': if my_instance.check_empty(): print('The stack is empty.') else: print('The deleted value is : ', my_instance.pop_val()) elif operation == 'quit': break
输出
Menu push <value> pop quit What operation would you like to perform ? push 89 What operation would you like to perform ? push 43 What operation would you like to perform ? push 76 What operation would you like to perform ? push 56 What operation would you like to perform ? pop The deleted value is : 56 What operation would you like to perform ? quit
解释
创建一个 ‘Stack_structure’ 类,用于初始化一个空列表。
定义一个 ‘check_empty’ 方法来查看堆栈是否为空。
定义另一个名为 ‘push_val’ 的方法,用于将元素添加到堆栈。
定义另一个名为 ‘pop_val’ 的方法,用于从堆栈中删除元素。
创建一个 ‘Queue_structure’ 类,用于初始化一个空列表并将列表大小指定为 0。
定义一个 ‘check_empty’ 方法来查看队列是否为空。
另一个名为 ‘enqueue_operation’ 的方法定义了将元素添加到队列的方法。
定义了另一个名为‘dequeue_operation’的方法,用于从队列中删除元素。
定义了另一个名为‘size_calculate’的方法,用于确定队列的大小。
定义了此‘Stack_structure’的一个实例。
给出了四个选项 - 菜单、推送、弹出和退出。
根据用户给出的输入,对堆栈的元素执行操作。
输出显示在控制台上。