算法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(){}
        
    }
}

 

posted @ 2018-01-22 19:07  meteorst  阅读(164)  评论(0编辑  收藏  举报