zoukankan      html  css  js  c++  java
  • 5, java数据结构和算法: 栈 , 入栈, 出栈, 正序遍历,,逆序遍历

    直接上代码:

      class ArrayStack{
        //用数组模拟栈
        int maxSize;
        int[] stack;
        int top = -1;//表示栈顶
    
        public ArrayStack(int maxSize) {
            this.maxSize = maxSize;
            this.stack = new int[maxSize];
        }
    
        //1, 入栈
        public void pushStack(int value){
            //判断是否满
            if(IsFull()){
                System.out.println("栈满了,不能添加");
                return;
            }
            top++;
            stack[top] = value;
        }
    
        //2, 出栈
        public int popStack() throws Exception {
            if(IsEmpty()){
                throw  new Exception("栈为空,不能出栈");
            }
            int value = stack[top];
            top--;
            return value;
        }
        //3. 栈的遍历
        public void show(){
            if(stack.length == 0){
                System.out.println("栈空,不能遍历");
                return;
            }
            for (int i = top; i >= 0; i--) {
                System.out.println(stack[i]);
            }
    
        }
        private boolean IsFull() {
            return top == maxSize-1;
        }
        private boolean IsEmpty(){
            return top == -1;
        }
    
        //4, 栈的逆序遍历
        public void resverShow(){
            if(stack.length == 0){
                System.out.println("栈空,不能遍历");
                return;
            }
            for (int i = 0; i <= top; i++) {
                System.out.println(stack[i]);
            }
        }
    }
    

    测试代码:

        public static void main(String[] args) throws Exception {
            ArrayStack stack = new ArrayStack(4);
            stack.pushStack(1);
            stack.pushStack(2);
            stack.pushStack(3);
            stack.pushStack(4);
    
            stack.show();//4-3-2-1  先进后出
    
            System.out.println("========");
            stack.popStack();
            stack.show();//3-2-1
            System.out.println("==========");
            stack.resverShow();//1-2-3
        }
    

    测试结果:

  • 相关阅读:
    BZOJ 1218: [HNOI2003]激光炸弹( 前缀和 + 枚举 )
    BZOJ 1878: [SDOI2009]HH的项链( BIT )
    BZOJ 1054: [HAOI2008]移动玩具( BFS )
    js-提取行间元素
    vim的三种模式的基本操作
    Linux的高级命令
    Linux的进阶命令
    Linux的基本命令
    Linux常见的文件目录结构
    js-操作属性
  • 原文地址:https://www.cnblogs.com/lvcai/p/13021835.html
Copyright © 2011-2022 走看看