class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.offer(x);
}
public int pop() {
dumpQueue();
return queue.poll();
}
public int top() {
dumpQueue();
int ans = queue.peek();
queue.offer(queue.poll());
return ans;
}
public boolean empty() {
return queue.isEmpty();
}
private void dumpQueue() {
//把size-1个元素压到队列尾,现在队列头部元素就是栈顶
int size = queue.size();
while (--size > 0) {
queue.offer(queue.poll());
}
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
class MyStack {
Queue<Integer> mainQueue;// 和栈的出栈顺序保持一致
Queue<Integer> auxiliaryQueue;// 辅助队列
public MyStack() {
mainQueue = new LinkedList<>();
auxiliaryQueue = new LinkedList<>();
}
// 保持出端和栈一样
public void push(int x) {
auxiliaryQueue.offer(x);
while (!mainQueue.isEmpty()) {
auxiliaryQueue.offer(mainQueue.poll());
}
// 交换主队列和辅助队列 可以把名字看作是指针
Queue<Integer> temp = mainQueue;
mainQueue = auxiliaryQueue;
auxiliaryQueue = temp;
}
public int pop() {
return mainQueue.poll();
}
public int top() {
return mainQueue.peek();
}
public boolean empty() {
return mainQueue.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
栈和队列的实现和增删查的函数是什么