题目:
使用栈实现队列的下列操作:
- push(x) – 将一个元素放入队列的尾部。
- pop() – 从队列首部移除元素。
- peek() – 返回队列首部的元素。
- empty() – 返回队列是否为空。
示例:
代码:
- 解法一
//思路:两个栈进行pop和peek操作
class MyQueue {
Stack<Integer> s1;
Stack<Integer> s2;
/** Initialize your data structure here. */
public MyQueue() {
s1 = new Stack<Integer>();
s2 = new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) { //画图很好理解 给字符串abc 经过两个栈的操作 实际存入栈中元素顺序为bottom[c b a]top
while (!s1.empty()) s2.push(s1.pop()); //将s1栈中元素都从S1栈放到s2栈中,
s1.push(x); //最新进栈的元素放入s1中
while (!s2.empty()) s1.push(s2.pop()); //再将s2栈中的元素放回s1中
return;
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return s1.pop();
}
/** Get the front element. */
public int peek() {
int ret = s1.pop(); //
s1.push(ret);
return ret;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.empty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
- 解法二
class MyQueue {
Stack<Integer> s1, s2;
/** Initialize your data structure here. */
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
while (!s1.isEmpty()) {
s2.push(s1.pop()); //将S1中的元素进栈到S2中
}
int output = s2.pop();
while (!s2.isEmpty()) { //在恢复S1中元素
s1.push(s2.pop());
}
return output;
}
/** Get the front element. */
public int peek() { //与pop()思路相同
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
int output = s2.peek();
while (!s2.isEmpty()) {
s1.push(s2.pop());
}
return output;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/