# 队列
class Queue(object):
def __init__(self):
self.items = []
def enqueue(self, value):
self.items.insert(0, value)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
# 栈
class Stack(object):
def __init__(self):
self.items = []
def push(self, value):
self.items.append(value)
def pop(self):
return self.items.pop(0)
# 两个队列实现一个栈
class QueueStack(object):
def __init__(self):
self.q1 = Queue()
self.q2 = Queue()
def push(self, value):
self.q1.enqueue(value)
def pop(self):
if self.q1.size() == 0:
return None
while self.q1.size() > 1:
self.q2.enqueue(self.q1.dequeue())
result = self.q1.dequeue()
self.q1, self.q2 = self.q2, self.q1
return result
Python实现队列,栈,两个队列构造一个栈
最新推荐文章于 2021-07-27 10:13:43 发布