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

来源:互联网 发布:淘宝店铺简介 编辑:程序博客网 时间:2024/06/03 21:08

T:

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

栈的特性是先进后出,队列的是先进先出,知道这点,基本上都能想到怎么做了。。。
还是说一下步骤:

  1. 队列的push()操作,就直接在stack1上进行栈的push()操作即可;
  2. 队列的pop()操作,其实就是得到stack1中最底下的那个元素,怎么得到呢?先把上面逐个退出的元素一个个放在另一个栈stack2中;
  3. 当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
原创粉丝点击