LeetCode #225 Implement Stack using Queues (队列实现栈)

题目:

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.

 

分析:

使用队列实现栈的数据结构。

1个队列。入栈时,先将要入栈的元素添加到队尾,然后将除了这个元素之外的所有元素依次出队,再入队。这样可以保证新入栈的元素总是在队列的最前面。

出栈时,直接出队即可。

 

代码:

Java