您的位置:首页 > Web前端

《剑指offer》牛客网java题解-用两个栈实现队列

2017-08-12 20:58 295 查看
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

这是一道比较经典的题,解法有多种,同样的还有用两个队列实现栈,leetcode上的原题。

此解法是push的时候把stack1弹向stack2,然后再从stack2弹回来。

mport java.util.Stack;

public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int node) {
while(!stack1.isEmpty())
{
stack2.push(stack1.pop());
}
stack2.push(node);
while(!stack2.isEmpty())
{
stack1.push(stack2.pop());
}
}

public int pop() {
return stack1.pop();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: