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(){}
            
        }
    }
  • 相关阅读:
    CString::GetLength()获得字节数
    Altium Designer 总线式布线
    Altium 原理图出现元件 “Extra Pin…in Normal of part ”警告
    编辑结束后收回键盘
    storybody中页面跳转
    改变tabBarItem颜色
    改变Button文字和图片的位置
    添加视图模糊效果(高斯模糊)
    ios开发获取SIM卡信息
    IOS 清除UIWebview的缓存以及cookie
  • 原文地址:https://www.cnblogs.com/meteorst/p/8330650.html
Copyright © 2011-2022 走看看