剑指offer--7.栈和队列

本文介绍如何使用两个栈实现队列的功能,并探讨了利用两个队列来模拟栈的操作方法。通过具体代码示例展示了数据结构转换的原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:用两个栈实现队列
/*
 * 用两个栈实现队列
 * 思路: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()); 
    }
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值