zoukankan      html  css  js  c++  java
  • 剑指offer五之用两个栈实现队列

    一、题目

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

    二、思路

          1、Push操作:将数据直接压入stack1即可

          2、Pop操作:将stack1中的数据全部弹出压入到stack2中,然后将stack1中的数据全部弹出即可

          注意:要将stack1中的数据全部压入到stack2中后,才能将stack2中的数据弹出

    三、代码 

    1、解决方法

    import java.util.Stack;
    
    public class Solution {
    
        Stack<Integer> stack1 = new Stack<Integer>();//栈1
        Stack<Integer> stack2 = new Stack<Integer>();//栈2
    
        public void push(int node) { //push操作
            stack1.push(node);
        }
    
        public int pop() {  //pop操作
            if (stack1.empty() && stack2.empty()) {
                throw new RuntimeException("Queue is empty!");
            }
            if (stack2.empty()) {
                while (!stack1.empty()) {
                    stack2.push(stack1.pop());
                }
            }
            return stack2.pop();
        }
    }
    View Code

    2、测试方法

    public class TestMain {
        public static void main(String[] args) {
            int[] a={1,2,3,4,5};
    
            Solution solution=new Solution();
    
            for(int i=0;i<a.length;i++){
                solution.push(a[i]);  //push的顺序1 2 3 4 5
            }
            for(int j=0;j<a.length;j++){
               int val= solution.pop();
                System.out.print(val+" ");  //pop的顺序 1 2 3 4 5
            }
        }
    }
    View Code

    ---------------------------------------------------------------------------------------------------------------------------------------------

    参考链接:https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6

  • 相关阅读:
    2014第5周一
    2014第4周日
    2014第4周六
    underscore.js
    2014第4周四
    2014第4周三
    2014年第2周二
    POj 3126 Prime Path
    Oracle EBS 入门
    HDU1698_Just a Hook(线段树/成段更新)
  • 原文地址:https://www.cnblogs.com/hezhiyao/p/7615584.html
Copyright © 2011-2022 走看看