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

Implement Stack using Queues

时间:2015-06-13 16:54:34      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/implement-stack-using-queues/

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Notes:

    • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
    • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
    • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

解题思路:

用了俩queue,思路就很明确了。需要peek或者pop的时候,将一个queue中的元素插入另一个queue,直到只剩一个了,这样才能获得尾端的元素。

也可以只用一个queue,但是在push的时候,就将所有元素立刻反向。

崩溃的是,Queue这个interface,居然没有empty()的方法,连size()的方法都没有。

class MyStack {
    LinkedList<Integer> queue1 = new LinkedList<Integer>();
    LinkedList<Integer> queue2 = new LinkedList<Integer>();
    
    // Push element x onto stack.
    public void push(int x) {
        if(queue1.size() > 0) {
            queue1.offer(x);
        } else {
            queue2.offer(x);
        }
    }

    // Removes the element on top of the stack.
    public void pop() {
        if(queue1.size() == 0) {
            LinkedList<Integer> temp = queue1;
            queue1 = queue2;
            queue2 = temp;
        }
        while(queue1.size() > 1) {
            queue2.offer(queue1.poll());
        }
        queue1.poll();
    }

    // Get the top element.
    public int top() {
        if(queue1.size() == 0){
            LinkedList<Integer> temp = queue1;
            queue1 = queue2;
            queue2 = temp;
        }
        while(queue1.size() > 1) {
            queue2.offer(queue1.poll());
        }
        int res = queue1.peek();
        queue2.offer(queue1.poll());
        return res;
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return queue1.size() == 0 && queue2.size() == 0;
    }
}

 

Implement Stack using Queues

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4573541.html

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