考研数据结构

用队列实现栈

2018-12-04  本文已影响5人  飞白非白

/**
Description

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

*/
class MyStack {
    /** Initialize your data structure here. */
    private LinkedList<Integer> q1 = new LinkedList<>();
    public MyStack() {
        q1 = new LinkedList<Integer>();
    }

    /** Push element x onto stack. */
    public void push(int x) {
        q1.add(x);
        int size = q1.size();
        while(size > 1){
            q1.add(q1.remove());
            size--;
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return q1.remove();
    }

    /** Get the top element. */
    public int top() {
        return q1.peek();
    }

    /** Returns whether the stack is empty. */
    public boolean empty() {
        return q1.isEmpty();
    }
}

上一篇下一篇

猜你喜欢

热点阅读