两个栈实现队列及两个队列实现栈

本文详细解释了如何利用两个栈实现队列操作,通过栈的先进后出特性转换为队列的先进先出特性。同时,阐述了如何使用两个队列来实现栈的先进后出特性。文中提供了具体代码实现,帮助读者理解这些数据结构的底层逻辑。

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

两个栈实现队列及两个队列实现栈:

两个栈实现队列:将一个栈内的数据倒到另一个栈里面,并弹出
两个队列实现栈:将一个队列里面的前(len-1)个数据添加到另一个队列,并弹出该队列的最后一个元素

public class Queue {

	private static Stack<Integer> stack = new Stack<Integer>();
	private static Stack<Integer> stack2 = new Stack<Integer>();

	public static void main(String[] args) {
		add(1);
		add(2);
		System.out.println(poll());
		add(3);
		System.out.println(poll());
	}

	private static void add(int value) {
		stack.push(value);
	}

	private static Integer poll() {
		if (stack.isEmpty()) {
			try {
				throw new Exception("queue is emtry");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		while (!stack.isEmpty()) {
			stack2.push(stack.pop());
		}
		return stack2.pop();
	}
}


public class Stack {

	private static Queue<Integer> queue = new ArrayDeque<Integer>();
	private static Queue<Integer> queue2 = new ArrayDeque<Integer>();

	public static void main(String[] args) {
		push(1);
		push(2);
		System.out.println(pop());
		push(3);
		push(4);
		System.out.println(pop());
		push(5);
		System.out.println(pop());
	}

	public static void push(int value) {
		while (queue.isEmpty()) {
			queue2.add(value);
			return;
		}
		while (queue2.isEmpty()) {
			queue.add(value);
			return;
		}
	}

	public static Integer pop() {
		if (queue.isEmpty() && queue2.isEmpty()) {
			try {
				throw new Exception("stack is emtry");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (queue2.isEmpty()) {
			while (queue.size() > 1) {
				queue2.add(queue.poll());
			}
			return queue.poll();
		}

		if (queue.isEmpty()) {
			while (queue2.size() > 1) {
				queue.add(queue2.poll());
			}
			return queue2.poll();
		}
		return null;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值