剑指offer第5题

/**
 * 目标:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 * 思路:
 * 队列是先进先出的数据结构
 * 栈是先进后出的数据结构
 * 当把一个stack倒进另一个stack就变成了先进先出
 * 注意:怎么使得整个算法是可以循环的
 * 入队时,把node放入队尾,可以先把stack倒过来,再插入node,记得恢复原样
 * 出队时,直接pop即可
* 代码:
*/ public class Solution5 { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { // if (stack1.empty() && stack2.empty()) { // stack1.push(node); // return; // } while (!stack2.empty()) { stack1.push(stack2.pop()); } stack1.push(node); while (!stack1.empty()) { stack2.push(stack1.pop()); } } public int pop() { return stack2.pop(); } }
原文地址:https://www.cnblogs.com/Adam-Ye/p/13451126.html