1力扣题做题笔记及复盘--225. 用队列实现栈(队列)
225. 用队列实现栈 - 力扣(LeetCode)
1、使用队列实现栈的下列操作:
- offer(x) -- 元素 x 入栈
- poll() -- 移除栈顶元素
- peek() -- 获取栈顶元素
- isEmpty() -- 返回栈是否为空
2、思路:
主要在添加元素方法中,队列的方式是先进先出,栈的方式是先进后出,那要将队列实现栈的效果,就要添加的元素,放在队列最前面。那么我的想法是先将新元素入队,然后最前面的元素出队放在队尾,以此类推,直到新元素在最前,那么就实现了后进先出的效果,剩下的peek()、isEmpty()、pop()直接出将队列操作就好。
3、代码:
1 class MyStack { 2 Queue<Integer> queue; 3 4 5 public MyStack() { 6 queue = new LinkedList<Integer>(); 7 8 } 9 //循环操作,直到新添加元素的位置 10 public void push(int x) { 11 queue.offer(x); 12 int size = queue.size(); 13 for(int i=0;i<size-1;i++){ 14 queue.offer(queue.poll()); 15 } 16 } 17 18 public int pop() { 19 return queue.poll(); 20 } 21 22 public int top() { 23 return queue.peek(); 24 } 25 26 public boolean empty() { 27 return queue.isEmpty(); 28 } 29 30 31 }
4、总结
队列的实现:Queue<T> que = new LinkedList<>();