1. 题目分析
题目已经给的很明显了,用两个栈来实现队列的功能,我们知道,栈和队列的特性是相反的,栈是先进先出,队列是后进先出,我们可以从两个角度来解决问题,一个是出栈,一个是入栈
2.1. 从入栈的角度分析
仔细想想,栈是先进先出,那么我们只需要把先进的元素变成后进的元素,也就是说将先进的元素压到栈底,那是不是就可以实现先进后出的队列了?下面给出图解
1.2. 从出栈的角度分析
栈是先进先出,那么我们让原本应该先出的元素,最后出,那是不是也可以实现队列的性质呢?下面给出图解
2. 代码实现
2.1. Python代码
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack1 = []
self.stack2 = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
if len(self.stack1) == 0:
self.stack1.append(x)
for i in self.stack2:
self.stack1.append(i)
self.stack2 = []
else:
self.stack2.append(x)
for i in self.stack1:
self.stack2.append(i)
self.stack1 = []
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if len(self.stack1) != 0:
return self.stack1.pop()
else:
return self.stack2.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
if len(self.stack1) != 0:
return self.stack1[-1]
else:
return self.stack2[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
if len(self.stack1) == 0 and len(self.stack2) == 0:
return True
else:
return False
2.2. Java代码
import java.util.Stack;
public class MyQueue {
Stack stack1 = new Stack();
Stack stack2 = new Stack();
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
if(stack1.size() == 0){
stack1.add(x);
stack1.addAll(stack2);
stack2.clear();
}else{
stack2.add(x);
stack2.addAll(stack1);
stack1.clear();
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(stack1.size() != 0){
return (int) stack1.pop();
}else{
return (int) stack2.pop();
}
}
/** Get the front element. */
public int peek() {
if(stack1.size() != 0){
return (int) stack1.peek();
}else{
return (int) stack2.peek();
}
}
/** Returns whether the queue is empty. */
public boolean empty() {
if(stack1.size() == 0 && stack2.size() == 0){
return true;
}else{
return false;
}
}
}