232. Implement Queue using Stacks

Posted optor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了232. Implement Queue using Stacks相关的知识,希望对你有一定的参考价值。

原题链接: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的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 232. Implement Queue using Stacks

LeetCode 232. Implement Queue using Stacks

232.Implement Queue using Stacks

232. Implement Queue using Stacks

232. Implement Queue using Stacks

232. Implement Queue using Stacks