两个队列实现栈,两个栈实现队列

博客介绍了用两个队列实现栈和用两个栈实现队列的方法。用两个队列实现栈时,借助辅助队列,按特定规则操作可实现栈的弹出顺序;用两个栈实现队列,需一个压栈栈和一个弹栈栈,遵循特定原则将元素在两栈间转移,以实现队列结构。

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

1、两个队列实现栈

思路:有两个队列,一个队列data,一个辅助队列help,我们只把数字加入到data中,在从data弹出元素之前,把最后加入元素之前的元素先全部压进help队列,然后data再做弹栈操作,就可以使得弹出的是最后一个压入的元素。接着,data和help交换引用,data将除了最后一个元素以外的所有元素全部压进help中,再做弹栈操作。以此类推。

import java.util.LinkedList;
import java.util.Queue;

public class Test{
	private Queue<Integer> data;
	private Queue<Integer> help;
	
	public Test() {
		this.data=new LinkedList<Integer>();
		this.help=new LinkedList<Integer>();
	}
	
	public void push(int obj) {
		data.add(obj);
	}
	
	public int peek() {
		if(data.isEmpty()) {
			throw new ArrayIndexOutOfBoundsException("The stack is empty");
		}
		while(data.size()>1) {
			help.add(data.poll());
		}
		int res=data.poll();
		help.add(res);//不抹除该res
		swap();
		return res;
	}
	
	public int pop() {
		if(data.isEmpty()) {
			throw new ArrayIndexOutOfBoundsException("The stack is empty");
		}
		while(data.size()>1) {
			help.add(data.poll());
		}
		int res=data.poll();
		swap();
		return res;
	}
	
	public void swap() {
		Queue<Integer> tmp=help;
		help=data;
		data=tmp;
	}
	public static void main(String[] args) {
		Test t=new Test();
		t.push(1);
		t.push(3);
		t.push(5);
		t.push(7);
		System.out.println(t.pop());
		System.out.println(t.pop());
	}
		
}

输出:
7
5

2、两个栈实现队列

思路:两个栈,一个push栈专门用来压栈,一个pop栈专门用来弹栈。将数字依次压入push栈,push栈再将栈中元素全部倒入pop栈,通过pop栈弹出即可实现队列结构。
但有两个原则需要遵循
1)push栈若要向pop栈倒东西,一定要一次性倒完,不要倒一半。否则会导致出队列顺序出错。
2)如果pop栈有东西push栈一定不要向pop栈倒东西。

import java.util.Stack;

public class Test{
	private Stack<Integer> push;
	private Stack<Integer> pop;
	
	public Test() {
		this.push=new Stack<Integer>();
		this.pop=new Stack<Integer>();
	}
	
	public void push(int obj) {
		push.push(obj);
		dao();//什么时候发生倒数据的行为都无所谓,只要满足两个原则就不会出错
	}
	
	public int peek() {
		if(pop.isEmpty()&&push.isEmpty()) {
			throw new ArrayIndexOutOfBoundsException("The stack is empty");
		}
		dao();
		return pop.peek();
	}
	
	public int poll() {
		if(pop.isEmpty()&&push.isEmpty()) {
			throw new ArrayIndexOutOfBoundsException("The stack is empty");
		}
		dao();
		return pop.pop();
	}
	//倒数据的行为要遵循以下两个原则
	public void dao() {
		if(!pop.isEmpty()) {
			return ;
		}
		while(!push.isEmpty()) {
			pop.push(push.pop());
		}
	}

	public static void main(String[] args) {
		Test t=new Test();
		t.push(1);
		t.push(3);
		t.push(5);
		t.push(7);
		System.out.println(t.poll());
		System.out.println(t.poll());
	}
		
}

输出:
1
3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值