《剑指offer》——用两个栈实现队列
来源:互联网 发布:淘宝店铺简介 编辑:程序博客网 时间:2024/06/03 21:08
T:
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
栈的特性是先进后出,队列的是先进先出,知道这点,基本上都能想到怎么做了。。。
还是说一下步骤:
- 队列的push()操作,就直接在stack1上进行栈的push()操作即可;
- 队列的pop()操作,其实就是得到stack1中最底下的那个元素,怎么得到呢?先把上面逐个退出的元素一个个放在另一个栈stack2中;
- 当stack1为空的时候,stack2的栈顶元素,就是要取得的元素,用栈的pop()操作取出,在将该元素进行返回前,再将stack2中的元素,倒回到stack1中,然后将该元素返回,over.
code:
package niuke.sward2offer.queueBy2Stack; import java.util.Queue; import java.util.Stack; /** * T: 用两个栈实现队列 * * 题目描述 * 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。 * * date: 2015.11.6 19:27 * @author SSS * */ 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() { while (!stack1.empty()) { Integer tempNode = stack1.pop(); stack2.push(tempNode); } int result = stack2.pop(); while (!stack2.empty()) { stack1.push(stack2.pop()); } return result; } public static void main(String []args) { Solution solution = new Solution(); // solution.push(2); // solution.push(3); System.out.println(solution.pop()); solution.push(5); // System.out.println(solution.pop()); // System.out.println(solution.pop()); } }
0 0
- 《剑指offer》——用两个栈实现队列
- 《剑指offer》——用两个栈实现队列
- 剑指offer——用两个栈实现队列
- 用两个栈实现队列——剑指offer
- 剑指offer——用两个栈实现队列
- 剑指offer——用两个栈实现队列
- 剑指offer——用两个栈实现队列
- 剑指offer——用两个栈实现队列
- 剑指offer——用两个栈来实现队列
- 剑指offer—用两个栈实现队列
- 《剑指offer》—5、用两个栈实现队列
- 牛客网—剑指offer-用两个栈实现队列
- 牛客网—剑指offer-用两个栈实现队列
- 剑指offer(5)—用两个栈实现队列
- 剑指offer—用两个栈实现队列
- [剑指offer]用两个栈实现队列
- 【剑指offer】用两个栈实现队列
- 剑指offer--用两个栈实现队列
- TwoSum
- excel排版转换为印刷版pdf:使用自动行号还是人工设定行高
- 静态编联与动态编联总结
- Stack is one important segment of the process’s memory layout. It is a dynamic memory buffer portion
- CSS-网页字体缩放样式-webkit-text-size-adjust的用法详解
- 《剑指offer》——用两个栈实现队列
- platform驱动之probe函数
- 发本地广播
- springMvc3 + hibernate4 jar包
- oracle用户登录报错-bash: ulimit: open files: cannot modify limit: Operation not permitted
- ListView系列(七)——Adapter内的onItemClick监听器四个arg参数
- Codeforces Round #329 (Div. 2) D. Happy Tree Party
- Android layout布局的优化
- Apache ActiveMQ 不作为的问题