leetcode(61).225. Implement Stack using Queues

来源:互联网 发布:gta5麦克捏脸数据 编辑:程序博客网 时间:2024/05/18 15:26

题意:使用队列实现栈的基本操作。

初步分析:关键是要把那场景想象出来:

队列的判断空,推入,队头这些都很好办,和栈最大的区别就是取出元素

    出队<-  &1 &2 &3 &4 &5 @ <-入队

入栈仍然和入队一样,那么出栈就应该是取出@,但是出队却是取出&1。出肯定是要走左边出的,所以,前面所有的&是要先出的,出队的时候,再入队,就可以回来。

@ &1 &2 &3 &4 &5 变成这样,再把@出队。

注意:top是&5,所以在它出队的时候,要把这个值赋值给top.

class MyStack {    private Queue<Integer> q = new LinkedList();    int top;    // Push element x onto stack.    public void push(int x) {        q.offer(x);        top = x;    }    // Removes the element on top of the stack.    public void pop() {        int size = q.size();        while(size > 1)        {            if(size==2)                top = q.peek();            q.offer(q.poll());            size--;        }        q.poll();    }    // Get the top element.    public int top() {        return top;       }    // Return whether the stack is empty.    public boolean empty() {        return q.isEmpty();    }}


0 0
原创粉丝点击