剑指offer题解之五——用两个栈实现队列

2016-08-24  本文已影响106人  KaelQ

1.题目概述

2.解题思路

3.代码解释

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
     
    public void push(int node) {//push为正常的堆栈push
         stack1.push(new Integer(node));
    }
 
    public int pop() {
       if(stack2.empty()){ //如果stack2为空,stack1就全部出栈到stack2中。
           while(!stack1.empty()){
               stack2.push(stack1.pop());
           }
       }
       if(stack2.empty()){//stack1出栈到stack2中后依然为空,证明此时队列为空。
             System.out.println("队列为空");
       }  
       return stack2.pop().intValue();
 }
}
上一篇 下一篇

猜你喜欢

热点阅读