问题描述
题目分析
栈:先进后出
队列:先进先出
一个队列肯定是实现不了栈的,要两个队列来模拟出先进后出
假设
如果是栈的情况下
先出的应该是34
但是现在是队列,出的话我们只能先出12
那应该怎么做把12出出来放到第二个队列,23出出来放到第二个队列
那么队列1就剩了一个元素,直接出出去就可以了,就相当于栈出去的第一个元素34
现在假设要放45这个元素
记住一点,每次入数据的时候都入到那个不为空的队列
现在我们要出45,同理,先把12和23入到队列1,然后出45就可以了
1.入栈的时候,入到不为空的队列,刚开始都为空指定入到一个队列
2.出栈的时候,找到不为空的队列,出size-1个元素到另一个队列,剩下的这个元素就是出栈的元素
完整代码
class MyStack { private Queue<Integer> queue; private Queue<Integer> queue1; public MyStack() { queue = new LinkedList<>(); queue1 = new LinkedList<>(); } public void push(int x) { if(!queue.isEmpty()){ queue.offer(x); }else if(!queue1.isEmpty()){ queue1.offer(x); }else{ queue1.offer(x); } } public int pop() { if(empty()) return -1; if(!queue.isEmpty()){ int size = queue.size(); for(int i = 0; i < size-1; i++){ int val = queue.poll(); queue1.offer(val); } return queue.poll(); } if(!queue1.isEmpty()){ int size = queue1.size(); for(int i = 0; i < size-1; i++){ int val = queue1.poll(); queue.offer(val); } return queue1.poll(); } return -1; } //得到队头元素 public int top() { if(!queue.isEmpty()){ int val = -1; int size = queue.size(); for(int i = 0; i < size; i++){ val = queue.poll(); queue1.offer(val); } return val; } if(!queue1.isEmpty()){ int val = -1; int size = queue1.size(); for(int i = 0; i < size; i++){ val = queue1.poll(); queue.offer(val); } return val; } return -1; } public boolean empty() { return queue1.isEmpty() && queue.isEmpty(); } }