力扣链接
首先我们要了解栈和队列的机制栈和队列
解题思路:
首先我们知道,队列是先进先出,栈是后进先出。
然后我们用两个队列来解决。
一个队列为主队列,一个为辅助队列,当入栈操作时,我们先将主队列内容导入辅助队列,然后将入栈元素放入主队列队头位置,再将辅助队列内容,依次添加进主队列即可。
先往辅助队列q2中插入元素
如果 q1 为空的话直接让q1指向q2,q2指向q1
在往 q2中插入元素
此时q1不为空.那么遍历q1把元素全部放入q2
再让q1指向q2,q2指向q1
这样后出栈,获取栈头以及判断栈是否为空,只需要判断队列q1就ok了
class MyStack {
public Queue<Integer> q1;
public Queue<Integer> q2;
/** Initialize your data structure here. */
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
q2.offer(x);
while (!q1.isEmpty()) {
q2.offer(q1.poll());
}
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.poll();
}
/** Get the top element. */
public int top() {
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}