题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
一开始的思路:用stack1做push操作。当pop操作时,先将stack2中元素清空,然后将stack1中的数据全部放入stack2中,然后取出stack2栈顶元素,最后把stack2中剩下的元素又放回stack1中,代码如下:
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack1.empty()) return 0;
else{
if(!stack2.empty()) stack2.clear();
while(!stack1.empty()){
int tem=stack1.pop();
stack2.push(tem);
}
int num= stack2.pop();
while(!stack2.empty()){
int tem=stack2.pop();
stack2.push(tem);
}
return num;
}
}
}
但是运行后发现时间超时了。
问题在于每次出栈的时候都需要遍历全部元素两次,很耗时间。后来参考别人代码后,做了一些修改。当stack2为空时,需要把stack1中的全部元素放入stack2中,但是当stack2不为空时,只需要弹出stack2中的栈顶元素即可,这样就剩下了很多时间。代码如下:
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack1.empty()&&stack2.empty()) throw new RuntimeException("Queue is empty!");
else
{
if(stack2.empty()) //当stack2中没有元素时,需要将stack1中元素导入
{
while(!stack1.empty())
{
int tem=stack1.pop();
stack2.push(tem);
}
return stack2.pop();
}
else return stack2.pop(); //stack2不为空时,直接返回栈顶元素
}
}
}