队列:先进先出。
栈:先进后出。
使用栈模拟队列:使用两个栈入栈,和出栈,stackin,stackout,入队列时,将元素存入stackin,进行压栈操作,当需要出队列时,使用stackout将入栈中的元素存入出栈中,这时候栈中元素的顺序就和出队的顺序一致,但是前提是需要注意的是,出队和入队是间隔执行的,所以说如果斤西瓜出队操作时,需要判断出栈是否为空,如果不为空直接出栈,如果为空就需要循环及那个入栈中的元素压入出战之中。
class MyQueue {
//存放入队列的元素
private Stack<Integer> stackin;
//存放出队列的元素
private Stack<Integer> stackout;
public MyQueue() {
this.stackin=new Stack<>();
this.stackout=new Stack<>();
}
public void push(int x) {
stackin.push(x);
}
public int pop() {
//如果出队列为空说明上次进入队列的元素,进入了入栈,
//但是还没有进入出栈
if(stackout.isEmpty()){
//将入栈中元素放入出栈中
while(!stackin.isEmpty()){
stackout.push(stackin.pop());
}
}
//当入栈为空时,出栈就可以弹出元素,执行出队列操作
return stackout.pop();
}
public int peek() {
//查看队列头部元素,但是注意,并不是直接拿出
//将入栈中元素放入出栈中
if(stackout.isEmpty()){
while(!stackin.isEmpty()){
stackout.push(stackin.pop());
}
}
return stackout.peek();
}
public boolean empty() {
return stackin.isEmpty()&&stackout.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();
*/
使用队列实现栈,惯性思维可能会认为需要两个队列,没错,两个队列是可以实现栈,但是一个队列也同样可以,因为队列两头都是开的,为满足栈的出栈顺序,所以当元素入队列时,可以直接对当前元素的前面所有元素进行出队在进队操作。出队在进队之后,当前队列的元素出队顺序就刚好满足栈的出栈顺序,接下来就正常的操作即可。
class MyStack {
//使用一个队列来模拟栈
Queue<Integer> queue;
public MyStack() {
this.queue=new LinkedList<>();
}
public void push(int x) {
//入队列的时候就 将元素改编为栈
queue.offer(x);
int size=queue.size()-1;
while(size-- > 0){
queue.offer(queue.poll());
}
}
public int pop() {
//此时队列中的元素出对顺序已经和出栈顺序一致
//直接出就可以
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.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();
*/
Write The Demo Change The World!!
By 三条直线围墙