225. 用队列实现栈

题目:请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
思路:用一个队即可以实现栈
代码:
class MyStack {
static Queue queue ;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList();
}

/** Push element x onto stack. */
public void push(int x) {
    int size = queue.size();
    queue.offer(x);
    while(size>0){
        queue.offer(queue.poll());
        size--;
    }
}

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

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

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

}

posted @ 2021-07-21 17:29  for_ward  阅读(27)  评论(0)    收藏  举报