题目:用两个栈实现队列
/*
* 用两个栈实现队列
* 思路:A为入队列,B为出队列
* 入队列,入A即可;出队列,如果B不为空,直接弹出B中数据,如果B空,则依次弹出A中的数据放入B中,再弹B
*/
public class wr7stackAndqueue<E> {
Stack<Integer> stacka=new Stack<>();
Stack<Integer> stackb=new Stack<>();
public void push(int node){
stacka.push(node);
}
public int pop(){
if(stackb.isEmpty()){
while(!stacka.isEmpty()){
stackb.push(stacka.pop());
}
}
return stackb.pop();
}
public static void main(String []args){
wr7stackAndqueue<Integer> sq=new wr7stackAndqueue<Integer>();
sq.push(2);
sq.push(8);
sq.push(5);
System.out.println(sq.pop());
}
}
也可以用两个队列实现栈/*
* 两个队列实现栈
* 思路:q1入队列,q2出队列
* 入栈,入q1即可;出栈,如果q1中只有一个元素,让其出队列并输出,如果q1不只一个,则q1中所有元素出队列入q2,但最后一个不入q2直接输出
*/
public class wr7queueAndstack<E> {
private LinkedList<Integer> q1=new LinkedList<>();
private LinkedList<Integer> q2=new LinkedList<>();
public void push(int item){
q1.addLast(item);
}
public int pop(){
int re=0;
if(ssize()!=0){
if(!q1.isEmpty()){
toAnother();
re=q1.removeFirst();
}
else{
toAnother();
re=q2.removeFirst();
}
}
return re;
}
// 将不为空队列的元素移到空队列中,只留下最后一个用于输出
public void toAnother(){
if(!q1.isEmpty()){
while(q1.size()>1){
q2.add(q1.removeFirst());
}
}
else if(!q2.isEmpty()){
while(q2.size()>1){
q1.add(q2.removeFirst());
}
}
}
public int ssize(){
return q1.size()+q2.size();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
wr7queueAndstack stack=new wr7queueAndstack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.push(5);
stack.push(6);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}