利用队列来实现栈和利用栈来实现队列

一、如何只使用队列来实现栈结构

因为队列的结构是先进后出,而栈的数据结构特点是先进先出,所以我们可以搞两个队列,当一个队列进入另外一个队列的时候,只剩下一个元素,留着返回,然后这个队列再进入原来哪个队列只剩下一个元素等着返回,循环使用这个逻辑,即可完成。

	/*
	 * 两个队列实现栈结构
	 */
	public static class TwoQueuesStack {
		//data队列和help队列,使用的是双向链表来完成的
		private Queue<Integer> queue;
		private Queue<Integer> help;

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

		public void push(int pushInt) {
			queue.add(pushInt);
		}

		public int peek() {
			if (queue.isEmpty()) {
				throw new RuntimeException("Stack is empty!");
			}
			while (queue.size() != 1) {
				help.add(queue.poll());
			}
			int res = queue.poll();
			//因为不弹出 所以还得把它放进help栈里
			help.add(res);
			swap();
			return res;
		}

		public int pop() {
			if (queue.isEmpty()) {
				throw new RuntimeException("Stack is empty!");
			}
			//当data队列的长度不为1时往help队列中
			while (queue.size() != 1) {
				help.add(queue.poll());
			}
			//然后把队列的最后一个元素添加到res中
			int res = queue.poll();
			swap();
			return res;
		}
		
		//交换引用,目的就是,都能重复使用是Data队列往help队列里放值,并留下最后一个数留着返回
		private void swap() {
			Queue<Integer> tmp = help;
			help = queue;
			queue = tmp;
		}

	}

二、只利用栈来实现队列

因为栈是先进后出的,队列是先进先出的,所以也可以利用两个栈区实现队列这种数据结构就是先把数据放到push栈里,再把push栈里的数据倒入pop栈里,出栈只从pop栈里出,这样就实现了两个栈完成队列的功能,但是要注意的是,当pop中有数据的时候千万不要从push往pop栈里倒数据,因为数据顺序会出现问题,第二要满足push栈有数据一定一下倒完。

        /*
	 * 实现使用栈来完成队列的操作
	 */
	public static class TwoStacksQueue {
		private Stack<Integer> stackPush;
		private Stack<Integer> stackPop;

		public TwoStacksQueue() {
			stackPush = new Stack<Integer>();
			stackPop = new Stack<Integer>();
		}

		public void push(int pushInt) {
			stackPush.push(pushInt);
			dao();
		}

		public int poll() {
			if (stackPop.empty() && stackPush.empty()) {
				throw new RuntimeException("Queue is empty!");
			} else if (stackPop.empty()) {
				while (!stackPush.empty()) {
					stackPop.push(stackPush.pop());
				}
			}
			dao();
			return stackPop.pop();
		}

		public int peek() {
			if (stackPop.empty() && stackPush.empty()) {
				throw new RuntimeException("Queue is empty!");
			} else if (stackPop.empty()) {
				while (!stackPush.empty()) {
					stackPop.push(stackPush.pop());
				}
			}
			dao();
			return stackPop.peek();
		}
		//满足当当pop栈没数据和push栈一次全倒的前提下把push栈的数据倒入pop栈中
		public void dao(){
			if(stackPush.isEmpty()){
				while(!stackPop.isEmpty()){
					stackPop.push(stackPush.pop());
				}
			}
			
		}
	}
	


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值