225. 用队列实现栈

使用队列实现栈的下列操作:

push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-stack-using-queues

 1 import java.util.LinkedList;
 2 import java.util.Queue;
 3 
 4 public class QueueForStack {
 5     private Queue<Integer> queue = new LinkedList<>();
 6     public QueueForStack() {
 7         
 8     }
 9     
10     public void push(int x) {
11         queue.add(x);
12         int size = queue.size();
13         while(size > 1) {
14             queue.add(queue.poll());
15             size--;
16         }
17     }
18     
19     public int pop() {
20         return queue.poll();
21     }
22 
23     public int top() {
24         return queue.peek();
25     }
26     
27     public boolean empty() {
28         return queue.isEmpty();
29     }
30 }
无论有多困难,都坚强的抬头挺胸,人生是一场醒悟,不要昨天,不要明天,只要今天。不一样的你我,不一样的心态,不一样的人生,顺其自然吧
原文地址:https://www.cnblogs.com/xiyangchen/p/11173719.html