Day01
Idea:
1、维护两个队列 q1接收输入数据 q2作为输出队列
2、push操作,q1接收新来的数据,再将q2中存放的元素全部加入q1,此时q1 = new data + q2 data
3、将q1 和 q2的引用交换,始终保证q1为空接收新来数据
class MyStack {
private Queue<Integer> q1; //输入
private Queue<Integer> q2; //输出
private int top;
/** Initialize your data structure here. */
public MyStack() {
q1 = new LinkedList<Integer>();
q2 = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
q1.offer(x); //q1接收数据,将q2中所有数据复制到q1,保证先来的数据在后面,新来的数据在前面
while(!q2.isEmpty()){
q1.offer(q2.poll());
}
Queue temp = q1;
q1 = q2;
q2 = temp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q2.poll();
}
/** Get the top element. */
public int top() {
return q2.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q2.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();
*/