剑指offer——用两个栈实现队列

题目

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

实现及原理

  • 栈,具有先进后出的特点;而队列具有先进先出的特点
  • 通过两个栈实现队列的特点,那么一个栈就需要作为压入栈,一个栈作为弹出栈。压入数据进压入栈,弹出数据从弹出栈出。
  • 在弹出数据时,需要判断弹出栈中是否还有数据,若还有剩余数据未被弹出,则直接弹出数据。否则,需要从压入栈中将数据导入弹出栈,再进行数据的弹出。

参考代码

import java.util.Stack;

/**
 * 
 * @author LXH
 *
 */
public class StackToQueue {
	// 压入栈
    Stack<Integer> stack1 = new Stack<Integer>();
    // 弹出栈
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
    	stack1.push(node);
    }
    
    public int pop() {
    	// 如果两个队列均为空,则不能在进行弹出操作,抛出运行时异常。
    	if(stack1.empty() && stack2.empty()) {
    		throw new RuntimeException("Queue is Empty");
    	}
    	// 若弹出栈不为空,则直接从弹出站中弹出相应的数据即可。
    	if(!stack2.empty()) {
    		return stack2.pop();
    	}
    	// 否则,需要将数据从压入栈中倒进弹出栈。
    	while(!stack1.isEmpty()) {
    		stack2.push(stack1.pop());
    	}
    	return stack2.pop();
    }
    
    public static void main(String[] args) {
    	StackToQueue stackToQueue = new StackToQueue();
		
    	stackToQueue.push(0);
    	stackToQueue.push(1);
    	stackToQueue.push(2);
    	stackToQueue.push(3);
    	stackToQueue.push(4);
    	stackToQueue.push(5);
    	stackToQueue.push(6);
		
		System.out.println(stackToQueue.pop());
		System.out.println(stackToQueue.pop());
		System.out.println(stackToQueue.pop());
		System.out.println(stackToQueue.pop());
		System.out.println(stackToQueue.pop());
	}
}

运行结果

 

       本题作为剑指offer中的题目,还是很受面试官们的青睐的,前一段时间的京东面试官就问到了这个题目的变形题目,不过万变不离其宗。把握住其中心思想,相信其他变形题目大家也是可以解决的。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值