数据结构与算法(JAVA版)2_7:使用队列实现栈的功能

题目:使用队列实现栈的功能
思路:使用两个队列,比如我要输入(栈低)0,1,2,3,按照栈的性质,输出为3,2,1,0
第一步:初始化两个队列,queue和help;
第二步:把元素存入queue队列中[3,2,1,0] (方向- - ->),此时我需要输出3,具体做法是:
从queue队列中依次弹出0,1,2,将元素0,1,2依次存入help队列中[2,1,0] (方向- - ->),此时queue队列内容为[3],然后弹出queue中的3,此时queue为空
第三步:初始化一个temp队列,用于充当queue与help交换之间的媒介。

package com.inspire.chapter2;

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

public class TwoQueueImplementStack {
	// 使用两个队列实现栈
	public static class TwoQueueStack<T> {
		private Queue<T> queue;
		private Queue<T> help;

		public TwoQueueStack() {
			queue = new LinkedList<>();
			help = new LinkedList<>();
		}

		public void push(T value) {
			queue.offer(value);
		}

		public T poll() {
			while (queue.size() > 1) {
				help.offer(queue.poll());
			}
			T ans = queue.poll();
			Queue<T> temp = queue;// 此时queue为空
			// 重点来了
			queue = help;
			help = temp;
			return ans;
		}
	}

	public static void main(String[] args) {
		TwoQueueStack<Integer> stack = new TwoQueueStack<>();
		stack.push(0);
		stack.push(1);
		stack.push(2);
		System.out.println(stack.poll());
		stack.push(3);
		stack.push(4);
		System.out.println(stack.poll());
		System.out.println(stack.poll());
		System.out.println(stack.poll());
		System.out.println(stack.poll());

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Inspiration666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值