232.用栈实现队列
使用栈实现队列的下列操作:
push(x)
– 将一个元素放入队列的尾部。
pop()
– 从队列首部移除元素。
peek()
– 返回队列首部的元素。
empty()
– 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.InStack=[] #分别设置两个栈
self.OutStack=[]
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.InStack.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if self.OutStack==[]: #注意只有当出栈为空时,才进行trans!!!
self.trans()
return self.OutStack.pop(-1)
def trans(self):
while(self.InStack!=[]):
rear=self.InStack.pop(-1)
self.OutStack.append(rear)
def peek(self) -> int:
"""
Get the front element.
"""
if self.OutStack==[]:
self.trans()
return self.OutStack[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
if self.OutStack==[] and self.InStack==[]:
return True
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()
用队列实现栈
直接贴上代码吧!
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.InQueue=[]
self.TempQueue=[] #建立一个临时储存的栈
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.InQueue.append(x)
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
self.trans()
top=self.InQueue.pop(0) #原始栈出栈只剩1个元素后,复制临时栈到新的原始栈
self.InQueue=self.TempQueue
self.TempQueue=[]
return top
def trans(self):
while(len(self.InQueue)!=1):
front=self.InQueue.pop(0)
self.TempQueue.append(front)
def top(self) -> int:
"""
Get the top element.
"""
self.trans()
top=self.InQueue[0]
self.TempQueue.append(top)
self.InQueue=self.TempQueue
self.TempQueue=[]
return top
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
if self.InQueue==[]:
return True
return False
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()