首页 > 学院 > 开发设计 > 正文

[LeetCode] Implement Queue using Stacks

2019-11-15 01:05:45
字体:
来源:转载
供稿:网友
[LeetCode] Implement Queue using Stacks

国际惯例,先上题目:

Implement the following Operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

Notes:

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

这道题个人觉得属于比较有意思的一道题><还有一道类似的用queue来完成stack的,不过我还没有做到,暂且不说。

这道题比较好想到的方法是双stack法,因为刚好stack和queue的顺序是相反的。

试想建立两个stack,当把所有数据从stack a中转移到b的时候,其数据排列就会发生变化,这样一来就很好理解了。

不过也可以只建立一个stack,这里就需要swap来辅助,这个会比较节省时间一点。

不过我暂时只写了双stack的用法,下次有机会写下单stack的哈哈。

个人觉得这道题难点就在第一个method上,后面都很简单,直接套用stack的method即可。

class MyQueue {        Stack<Integer> a=new Stack<Integer>();    Stack<Integer> b=new Stack<Integer>();        // Push element x to the back of queue.    public void push(int x) {        //specail case        if(a.isEmpty()){            a.push(x);        }else{            while(!a.isEmpty()){                b.push(a.pop());            }            a.push(x);            while(!b.isEmpty()){                a.push(b.pop());            }        }            }    // Removes the element from in front of queue.    public void pop() {        a.pop();    }    // Get the front element.    public int peek() {        return a.peek();    }    // Return whether the queue is empty.    public boolean empty() {        return a.isEmpty();    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表