题目
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
思路
栈:先进后出
队列:先进先出
一个队列负责进队列,一个队列负责出队列。
代码
# 两个栈模拟队列的进、出
class Queue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def append_Tail(self, element):
self.stack1.append(element)
def delete_Head(self):
# 如果stack2不为空,直接弹出栈顶元素
if len(stack2) != 0:
self.stack2.pop()
elif len(stack2) == 0 and len(stack1) != 0:
while len(stack1):
# stack1元素全部压入stack2
data = stack1.pop()
stack2.append(data)
stack2.pop()
else:
raise ValueError('queue is empty!'_
相关题目:两个队列实现一个栈,也是类似的方法。
栈实现队列
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self._enqueue = []
self._dequeue = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self._enqueue.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if self.empty():
return
if len(self._dequeue) == 0:
# 出队的栈是空,将入队的元素push到出队栈
while len(self._enqueue) != 0:
self._dequeue.append(self._enqueue.pop())
# self._dequeue.pop()
# else:
# # 出队的栈有元素
# self._dequeue.pop()
return self._dequeue.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if self.empty():
return
if len(self._dequeue) == 0:
while len(self._enqueue) != 0:
self._dequeue.append(self._enqueue.pop())
return self._dequeue[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
if len(self._enqueue) == 0 and len(self._dequeue) == 0:
return True
else:
return False
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()