剑指offer【9】:用两个栈实现队列
文章目录
题目
用两个栈实现一个队列,完成队列的Push和Pop操作。
题解
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() throws Exception {
if(stack2.isEmpty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
if(stack2.empty()){
throw new IllegalArgumentException("链表为空");
}
return stack2.pop();
}
}
注意点
注意特殊情况。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论