剑指offer 用2个栈实现队列

来源:互联网 发布:php高级编程书籍 编辑:程序博客网 时间:2024/06/05 19:19

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。


解决方案:

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(new Integer(node));    }    public int pop() {        Integer r=null;        if(!stack2.isEmpty()){            r=stack2.pop();//如果stack2不是空的,则弹出第一个            //写上面一句的重要性:当多次弹出的时候,就要执行这一句        }else{            while(!stack1.isEmpty()){                stack2.push(stack1.pop());            }            if(!stack2.isEmpty()){                r=stack2.pop();            }        }        return r;    }}

或者

这是左程云的《程序员代码面试指南》的答案: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(stack1.empty()&&stack2.empty()){            throw new RuntimeException("Queue is empty!");        }        if(stack2.empty()){            while(!stack1.empty()){                stack2.push(stack1.pop());            }        }        return stack2.pop();    }}

原创粉丝点击