使用两个队列实现栈的Python程序
当需要使用两个队列实现栈时,需要一个“Stack_structure”类和一个“Queue_structure”类。这两个类中分别定义了用于向栈和队列添加和删除值的相应方法。
下面是演示:
示例
class Stack_structure:
def __init__(self):
self.queue_1 = Queue_structure()
self.queue_2 = Queue_structure()
def check_empty(self):
return self.queue_2.check_empty()
def push_val(self, data):
self.queue_1.enqueue_operation(data)
while not self.queue_2.check_empty():
x = self.queue_2.dequeue_operation()
self.queue_1.enqueue_operation(x)
self.queue_1, self.queue_2 = self.queue_2, self.queue_1
def pop_val(self):
return self.queue_2.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('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 56 What operation would you like to perform ? push 34 What operation would you like to perform ? push 78 What operation would you like to perform ? push 90 What operation would you like to perform ? pop The deleted value is: 90 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”的方法来确定队列的大小。
定义了两个“Queue_structure”的实例。
提供了四个选项:菜单、入栈、出栈和退出。
根据用户提供的输入,对栈的元素执行操作。
输出显示在控制台上。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP