用栈实现队列和用队列实现栈

  在面试中被问到这类题目,由于当时并没有太留心,栽了两次,实在不应该。总结到博客,方便后面翻出来时时复习。

用队列实现栈

  这里的思想是用两个队列实现一个栈,交替进行存储和弹出数据,很好的图解详见:点击打开链接

  关于这里队列的实现,可以用实现了Queue接口的ArrayDeque或者LinkedList,改一下import的包就好了。

import java.util.ArrayDeque;
import java.util.Queue;

public class TwoQueueStack {
	Queue<Integer> queue1 = new ArrayDeque<Integer>(); //两个队列实现一个栈
	Queue<Integer> queue2 = new ArrayDeque<Integer>();
	
	public void push(Integer element) {
		if(queue1.isEmpty() && queue2.isEmpty()) {  //两个队列均空,优先在第一个队列压入数据
			queue1.add(element);
		}
		else if(queue1.isEmpty()) {
			queue2.add(element);
		}
		else {
			queue1.add(element);
		}
	}
	
	public Integer pop() {
		if(queue1.isEmpty() && queue2.isEmpty()) {  //两个队列均空,弹出数据报错
			try {
				throw new Exception("Stack is Empty!");
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
		else if(queue1.isEmpty()) {
			while(queue2.size() > 1) {
				queue1.add(queue2.poll());
			}
			return queue2.poll();
		}
		else {
			while(queue1.size() > 1) {
				queue2.add(queue1.poll());
			}
			return queue1.poll();
		}
		return (Integer)null;  //对于两个队列均空情况返回null
	}
	
	public static void main(String[] args) {
		TwoQueueStack queueStack = new TwoQueueStack();
		queueStack.push(1);
		queueStack.push(2);
		queueStack.push(3);
		queueStack.push(4);
		System.out.println(queueStack.pop());
		System.out.println(queueStack.pop());
		queueStack.push(5);
		System.out.println(queueStack.pop());
	}
}


用栈实现队列

  这里的思想也是用两个栈实现一个队列,和上一种情况有点区别,第一个栈只负责存储数据,另一个栈只用于弹出数据。

import java.util.Stack;

public class TwoStackQueue {
	Stack<Integer> stack1 = new Stack<>();
	Stack<Integer> stack2 = new Stack<>();
	
	public void add(Integer element) {
		stack1.push(element);		
	}
	public Integer poll() {		
		if(stack2.isEmpty()) {  //判断第二个栈为空,第一个栈中元素弹出到第二个栈
			while(stack1.size() > 0) {
				stack2.push(stack1.pop());
			}			
		}
		if(stack2.isEmpty()) {  //判断第二个栈仍为空,报错
			try {
				throw new Exception("Queue is Empty");
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
		return stack2.pop();
	}
	public static void main(String[] args) {
		TwoStackQueue stackQueue = new TwoStackQueue();
		stackQueue.add(1);
		stackQueue.add(2);
		stackQueue.add(3);
		System.out.println(stackQueue.poll());
		System.out.println(stackQueue.poll());
		stackQueue.add(5);
		System.out.println(stackQueue.poll());
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值