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(){}
            
        }
    }
  • 相关阅读:
    Android将ScrollView移动到最底部
    Android权限之sharedUserId和签名
    python接口使用及工具函数
    python模块(json、os、sys、random、string、time、hashlib)
    python内置函数
    python模块、函数变量及递归
    python数据类型集合及函数
    python文件操作及修改
    python字符类型操作及文件操作
    jmeter压测
  • 原文地址:https://www.cnblogs.com/meteorst/p/8330650.html
Copyright © 2011-2022 走看看