LeetCode 225用队列实现栈

408 阅读1分钟

用队列实现栈

LeetCode225用队列的形式实现栈的操作,队列是FIFO先进先出的模式,栈是FILO先进后出的模式。

简单思路

PUSH:使用一个标记位标记栈顶元素,直接enqueue到队列中即可,每次enqueue的元素就为栈顶元素。

POP:POP操作需要移除栈顶元素,dequeue只能出队栈底元素。循环从队列头将元素去除重新入队到队尾,同时保留倒数第二个元素标记栈顶元素,出队队首元素。

PEEK:直接返回标记元素

贴代码

class MyStack {
    Queue<Integer> q;
    int top_ele;
    /** Initialize your data structure here. */
    public MyStack() {
        q = new LinkedList<>();
        top_ele = 0;
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        q.offer(x);
        top_ele = x;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        int size = q.size();
        while (size > 2) {
            q.offer(q.poll());
            size --;
        }
        top_ele = q.poll();
        q.offer(top_ele);
        return q.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return top_ele;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return q.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */