【剑指offer】用两个栈实现队列
来源:互联网 发布:软件研发 高级工程师 编辑:程序博客网 时间:2024/06/03 23:45
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路
栈是先进后出,队列是先进先出,两个栈分别为stack1和stack2,入队时直接把节点推入stack1,出队时,根据栈和队列的特性,把stack1的元素一个个出栈,在一个个入栈到stack2中,此时satck2的出栈元素顺序正好是元素入队顺序。
代码
import java.util.Stack;public class Solution { Stack<Integer> stack1 = new Stack<Integer>();//入队列// Stack<Integer> stack2 = new Stack<Integer>();//出队列// public void push(int node) { stack1.push(node); } public int pop() { if (stack2.empty()) while(!stack1.empty()) stack2.push(stack1.pop()); return stack2.pop(); }
阅读全文
0 0
- [剑指offer]用两个栈实现队列
- 【剑指offer】用两个栈实现队列
- 剑指offer--用两个栈实现队列
- 剑指Offer-用两个栈实现队列
- 剑指offer:用两个栈实现队列
- 《剑指offer》用两个栈实现队列
- 用两个栈实现队列(剑指offer)
- 剑指 offer:用两个栈实现队列
- 【剑指Offer】用两个栈实现队列
- 剑指offer-用两个栈实现队列
- 《剑指offer》-用两个栈实现队列
- 剑指offer 用两个栈实现队列
- 剑指offer 用两个栈实现队列
- [剑指offer]用两个栈实现队列
- 剑指offer--用两个栈实现队列
- 剑指offer|用两个栈实现队列
- 【剑指offer】用两个栈实现队列
- 剑指offer----用两个栈实现队列
- iOS开发之如何手动销毁掉NavigationController中任意控制器
- 二叉树相关算法——创建、遍历、求深度和广度
- vs2017下搭建opengl es 3.0开发环境
- 昨天我开了个淘宝店
- 入职第一周总结
- 【剑指offer】用两个栈实现队列
- c++中任意类型的研究
- 单链表实现简单通讯录
- 求第n个斐波那契(fibonacci)数
- [UESTC851]方老师与素数
- 探秘Java中的String、StringBuilder以及StringBuffer
- 动态规划
- 《锋利的jQuery》读书笔记第二章(jQuery选择器)
- Django+Oracle环境搭建