zoukankan      html  css  js  c++  java
  • 算法4学习笔记(1):数组实现栈(java)

    不能调整数据大小的定容栈:

      实现代码:

    public class FixedStack<element>
    {
        private element[] a;
        private int N;
        public FixedStack(int num){
            a = (element[])new Object[num];
        }
        
        public boolean isEmpty(){
            return N == 0;
        }
        
        public int size(){
            return N;
        }
        
        public void push(element ele){
            
            a[N] = ele;
            N++;
        }
        
        public element pop(){
            N--;
            return a[N];
        }
    }

      测试代码:

    import java.util.Scanner;
    
    public class test
    {
        public static void main(String args[]){
            Scanner sc = new Scanner(System.in);
            
            FixedStack<String> b = new FixedStack<String>(100);
            
            while(sc.hasNext()){
                String c = sc.next();
                if(!c.equals("-")){
                    b.push(c);
                }else if(!b.isEmpty()){
                    System.out.print(b.pop()+" ");
                }
            }
            
        }
    }

      测试结果:

      输入:to be or not to - be - - that - - - is

      输出:to be not that or be

      可迭代栈(数组实现):

    import java.util.Iterator;
    
    public class FixedStack<element> implements Iterable<element>
    {
        private element[] a;
        private int N;
        public FixedStack(int num){
            a = (element[])new Object[num];
        }
        
        public boolean isEmpty(){
            return N == 0;
        }
        
        public int size(){
            return N;
        }
        
        public void push(element ele){
            
            a[N] = ele;
            N++;
        }
        
        public element pop(){
            N--;
            return a[N];
        }
        
        public Iterator<element> iterator(){
            return new arrayIterator();
        }
        
        private class arrayIterator implements Iterator<element>{
            private int i = N;
            public boolean hasNext(){ return i>0;}
            public element next(){return a[--i];}
            public void remove(){}
            
        }
    }
  • 相关阅读:
    xx
    java
    SAFe 4.0参考指南:精益软件与系统工程的规模化敏捷框架
    Scaled Agile Framework – SAFe for Lean Enterprises
    云宏信息科技股份有限公司
    k8s~kubectl常用命令
    springboot~mvn多个关联项目打包问题
    java~线程池的总结~续
    java~线程池的总结
    电子工程师必备:九大系统电路识图宝典
  • 原文地址:https://www.cnblogs.com/meteorst/p/8330650.html
Copyright © 2011-2022 走看看