两个队列实现一个stack
- q1只保持一个元素即可, 多余的转换到q2当中
- 出队列元素,有两种情况,
- q1不为空, 直接出队列
- 如果连续出队列 q1可能为空, 需要q2的部分元素放到q1当中去,
说白了就是元素捣鼓来捣鼓去的问题即可
class MyStack {
/** Initialize your data structure here. */
// 全部的数据逆转即可
Queue<Integer> q1;
Queue<Integer> q2;
public MyStack() {
q1=new LinkedList<>();
q2 =new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
// 添加元素即可
q1.offer(x);
for(int i=0;i<q1.size()-1;i++){
q2.offer(q1.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
top();
return q1.poll();
}
/** Get the top element. */
public int top() {
// 确保元素里面的
if(q1.isEmpty()){
//将q2当中的顶上部的元素捣鼓过来即可
for(int i=0;i<q2.size()-1;i++){
q2.offer(q2.poll());
}
q1.offer(q2.poll());
}
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty()&& 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();
*/
核心事项
将一个筒里面的元素捣鼓来捣鼓去
一个队列实现一个stack
没加入一个元素都是捣鼓捣鼓去就行,重置元素的基础顺序即可
两个stack实现一个队列
一个负责进入stack,另一个负责出stack,
只需要pop或者peek 元素的时候我们进行判断out stack是否有元素即可,如果有没有元素我们不断得向里面放入元素即可的情况
class MyQueue {
/** Initialize your data structure here. */
private Stack<Integer> in;
private Stack<Integer> out;
public MyQueue() {
in =new Stack<>();
out = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
// 只负责进入stack 即可
in.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
peek();
return out.pop();
}
/** Get the front element. */
public int peek() {
//如果in中有元素的情况
//处理前面的元素,
if(out.isEmpty()){
while(!in.isEmpty()){
out.push(in.pop());
}
}
return out.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/