首页 > 其他 > 详细

232. Implement Queue using Stacks

时间:2018-04-06 11:58:16      阅读:175      评论:0      收藏:0      [点我收藏+]

原题链接:https://leetcode.com/problems/implement-queue-using-stacks/description/
实现如下:

import java.util.Stack;

/**
 * Created by clearbug on 2018/4/5.
 *
 * 这只是最普通最简单的一种方法实现,官方答案里面的第二种方法真不错,整体上提高了时间效率!
 */
public class MyQueue {

    private Stack<Integer> stack1;

    private Stack<Integer> stack2;

    /** Initialize your data structure here. */
    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        while (!stack1.empty()) {
            stack2.push(stack1.pop());
        }
        stack2.push(x);
        while (!stack2.empty()) {
            stack1.push(stack2.pop());
        }
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return stack1.pop();
    }

    /** Get the front element. */
    public int peek() {
        return stack1.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack1.empty();
    }

}

232. Implement Queue using Stacks

原文:https://www.cnblogs.com/optor/p/8727014.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!