码迷,mamicode.com
首页 > 其他好文 > 详细

232. Implement Queue using Stacks

时间:2018-04-06 12:25:32      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:pre   tps   port   structure   clear   des   and   problems   created   

原题链接: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

标签:pre   tps   port   structure   clear   des   and   problems   created   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!