剑指offer系列----用两个栈实现一个队列

来源:互联网 发布:马云发明了几个软件 编辑:程序博客网 时间:2024/06/06 14:15
package offer;import java.util.Stack;/** * 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。 * @author liu * */public class TwoStackToQueue {    //创建两个栈    Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();    //push方法,模拟压入队列    public void push(int node){        stack1.push(node);    }    //pop方法,出队列方法,将第一个栈中的数据依次弹出,放入第二个栈之中    public int pop(int node){        //如果stack1 和 stack2 的size()都返回0,就抛出异常        if(stack1.empty() && stack2.empty()){            throw new RuntimeException("Queue is Empty!");        }        //如果stack2为空        if(stack2.empty()){            //将stack1中的所有数出栈,并压入stack2之中            while(!stack1.empty()){                stack2.push(stack1.pop());            }        }        //stack2出栈,形成先进先出的队列效果        return stack2.pop();    }}
0 0
原创粉丝点击