1.题目
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
(1)双队列
- 双队列解决该问题 ,push时,先把x导入queue2,判断queue1是否为空,降queue1中所以元素导入queue2,然后交换 queue1与queue2
- 队列的特点是先进先出,而栈是先进后出。那如何能让队列变成先进后出呢?其实只要在插入的时候能让插入的数插入到队列头,并且保持相对顺序不变就可以了。
class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
public MyStack() {
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
}
public void push(int x) {
queue2.offer(x); //后面插入时,保持插入值x始终在队列头
while (!queue1.isEmpty()) {
queue2.offer(queue1.poll());
}
//交换queue1 , queue2,保持queue1中实现栈
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.isEmpty();
}
}
(2)双队列
pop特殊处理
class MyStack {
/** Initialize your data structure here. */
Deque<Integer> que1;
Deque<Integer> que2;
public MyStack() {
que1 = new LinkedList<>();
que2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
que1.addLast(x); //先放辅助队列中
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int size = que1.size();
size--;
while(size-- > 0){ //将q1导入q2但是保留最后一个值
que1.addLast(que1.peekFirst());
que1.pollFirst();
}
int res = que1.pollFirst();
return res;
}
/** Get the top element. */
public int top() {
return que1.peekLast();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return que1.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();
*/
(3)优化
class MyStack {
Deque<Integer> que1;
Deque<Integer> que2;
/** Initialize your data structure here. */
public MyStack() {
que1 = new LinkedList<>();
que2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
que1.addLast(x); //先放辅助队列中
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return que1.pollLast();
}
/** Get the top element. */
public int top() {
return que1.peekLast();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return que1.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();
*/