题目描述
题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。
队列中的元素为int类型。
给定代码
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
}
public int pop() {
}
}
题解
这题的核心是取数据(pop),只要保证最先进入的数据在提供的两个栈之一的栈顶就能实现这个目标功能。
所以处理逻辑很简单:
- 每次push数据直接进栈1;
- 每次pop时,如果栈2为空,将栈1里的所有数据pop到栈2;
这样做可以让栈2里面的数据按照先后顺序排列(顶->底),
例如栈1:d c b a,转移到栈2后,就是a b c d。
所以这就保证了栈2的顶部绝对是最先进入的数据,就算期间栈1又有数据进入,它也是后来的数据,不会影响栈2的特性
- 如果栈2不为空,直接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.empty())
{
while(!stack1.empty())
{
stack2.push(stack1.pop());
}
}
return stack2.empty() ? 0 : stack2.pop();
}
}