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(){}
            
        }
    }
  • 相关阅读:
    apicloud教程
    apicloud教程3 (转载)
    apicloud教程2 (转载)
    apicloud教程1 (转载)
    API CLOUD 快捷键
    JS IIFE写法
    php事件驱动
    JQuery实践--Why JQuery
    Jquery实践--精读开篇
    python 实践--新闻聚合
  • 原文地址:https://www.cnblogs.com/meteorst/p/8330650.html
Copyright © 2011-2022 走看看