版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/littlehaes/article/details/91384541
welcome to my blog
剑指offer面试题9(java版):用两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路
- 创建两个栈stack1, stack2
- stack1只负责添加元素
- stack2只负责删除元素; 当stack2不为空时直接pop()栈顶元素即可, 当stack2为空时,先把stack1中的元素压入stack2,再pop()栈顶元素
复杂度
import java.util.Stack;
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(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
else{
return stack2.pop();
}
}
}