题解 | #用两个栈实现队列#

用两个栈实现队列

http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6

import java.util.Stack;

public class TwoStackQueueTest {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    /**
     * 从第一个栈只push
     * @param node
     */
    public void push(int node) {
        stack1.push(node);
    }

    /**
     * 从第二个栈删除,如果没有数据,则需要从第一个倒转数据过来。
     * 如果有数据,则直接删除,这样可以是的两个栈都存放数据。
     * @return
     */
    public int pop() {
        if (stack2.size()==0){
            while (stack1.size()>0) {
                stack2.push(stack1.pop());
            }
        }
        if (stack2.size()==0){
            return -1;
        }
        return stack2.pop();
    }

    public static void main(String[] args) {
        TwoStackQueueTest test = new TwoStackQueueTest();
        test.push(1);
        test.push(2);
        System.out.println(test.pop());
        System.out.println(test.pop());
    }
}
算法 文章被收录于专栏

数据结构和算法

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务