解题思路
1.队列先进先出
2.栈先进后出
3.数据进两次栈,两次先进后出相当于先进先出
4.stack1负责实现队列的进功能,Stack2实现队列的出功能
5.push()功能,通过stack1入栈实现
6.pop()功能实现过程中,若Stack2不为空,则直接弹出,如为空则将stack1中的数输出到stack2中然后再从stack2中弹出,从而保证始终是先进先出
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
代码实现
1 import java.util.Stack; 2 3 public class Solution { 4 Stack<Integer> stack1 = new Stack<Integer>(); 5 Stack<Integer> stack2 = new Stack<Integer>(); 6 7 public void push(int node) { 8 stack1.push(node); 9 } 10 11 public int pop() { 12 if(stack2.isEmpty()){ 13 while(!stack1.isEmpty()){ 14 stack2.push(stack1.pop()); 15 } 16 } 17 return stack2.pop(); 18 } 19 }