1、用两个栈实现队列
1.1、[牛客]用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
package jianzhioffer;
import java.util.Stack;
/**
* @author jiyongjia
* @create 2020/6/19 - 18:23
* @descp: P1: 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
*/
public class P1_Queue {
/*
* 我们知道,栈是先进后出,队列是先进先出的,那么要模拟队列就需要把两个栈连接起来使用。
* */
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
/*
1 我们需要在队列中添加一个元素的时候,就先直接放在stack1中即可了.在取的时候(从stack1拿出放入stack2后再取出)会满足先进先出
*/
public void push(int node) {
stack1.push(node);
}
/**
* 2 我们要取出一个队中元素,应该是取出先放入的元素先取出。所以,需要把stack1中的元素pop出后一一压入stack2,此时再从stack2中取出
* 栈顶元素,就是满足了先进stack1的元素先出来了。【先进stack1的元素是被放入栈底下的,当转入到stcak2中就出现在栈顶了,此时再pop,
* 就是满足了先进先出】
* @return
*/
public int pop() {
if (stack2.size()<=0){
while (stack1.size()!=0){
stack2.push(stack1.pop());
}
return stack2.pop();
}else {
return stack2.pop();
}
}
}
class CQueue {
Stack stack1 = new Stack<Integer>();
Stack stack2 = new Stack<Integer>();
public CQueue() {
}
//放入到stack1中,即在转移后就是放到了队尾
public void appendTail(int value) {
stack1.push(value);
}
public int deleteHead() {
//如果stack2中是空,就先把stack1的转移到stack2
if(stack2.size()<=0){
//转移的时候发现stack1也是空,就返回-1;
if(stack1.size() ==0){
return -1;
//stack1部署-1就一个个都转移到stack2
}else{
while(stack1.size()!=0){
stack2.push(stack1.pop());
}
return (int)stack2.pop();
}
//如果stack2不是空,就直接取
}else{
return (int)stack2.pop();
}
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/