1.题目
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
2.解题思路
将要放的数依次push到stack1中,将stack1中的数pop出来,再push到Stack2中
注意:只有stack2为空时,才可以往进push 新的值,否则顺序会乱;当其不为空直接进行pop
3.代码实现
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()){
if(stack1.empty()){
try {
throw new Exception("栈为空!");
} catch (Exception e) {
e.printStackTrace();
}
}else{
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
}
return stack2.pop();
}
public static void main(String[] args) {
Solution solution=new Solution();
solution.push(1);
solution.push(2);
solution.push(3);
System.out.println(solution.pop());
System.out.println(solution.pop());
System.out.println(solution.pop());
}
}
测试结果:
1
2
3