2019-03-19 java数据结构(一) 顺序表

一、对顺序表的说明:

根据代码,将顺序表理解为数组、ArrayList。

二、代码实现:

1、为了方便浏览,先定义一个接口,写上所有的方法。

public interface IList {
    void clear();
    boolean isEmpty();
    int size();
    Object get(int i) throws Exception;
    void insert(int i,Object o) throws Exception;
    int indexOf(Object o);//查看元素在什么位置
    void remove(int i) throws Exception;
    void display();
}

2、创建MyList 类,实现 IList接口

public class MyList implements IList{
    private Object[] listElem;
    //当前长度
    private int curLen;
    MyList(int maxSize){
        curLen=0;
        //初始化分配maxSize个存储单位
        listElem=new Object[maxSize];
    }
    @Override
    public void clear() {
        curLen=0;
    }
    @Override
    public boolean isEmpty() {
        return curLen==0;
    }
    @Override
    public int size() {
        return curLen;
    }
    @Override
    public Object get(int i) throws Exception {
        if(i<0||i>=curLen)
            throw new Exception("输入位置错误!!");
        return listElem[i];
    }
    @Override
    public void insert(int i, Object o) throws Exception {
        if(i>=listElem.length){
            throw new Exception("插入位置大于表的最大限度!!");
        }
        if(i>curLen || i<0){
            throw new Exception("插入位置不合法!!");
        }
        //后面不需要再加上if判断
        //从后到前,一个一个替代    
        for (int j = curLen-1; j >=i; j--) 
            listElem[j+1]=listElem[j];
        listElem[i]=o;
        curLen++;
    }
    @Override
    public int indexOf(Object o) {
        for (int i = 0; i <curLen; i++) {
            if(listElem[i].equals(o))
                return i;
        }
        return -1;
    }
    @Override
    public void remove(int i) throws Exception {
        if(i>=curLen || i<0){
            throw new Exception("删除位置不合法!!");
        }
        for (int j = i; j < curLen-1; j++) 
            listElem[j]=listElem[j+1];
        
        curLen--;
    }
    @Override
    public void display() {
        for (int i = 0; i <curLen; i++) {
            System.out.print(listElem[i]+" ");
        }
        System.out.println();
    }
}

3、码的过程中,还是存在多余的语句,实现方法的时候,适当地画下图,能让逻辑更加清晰 ,码的效率会高些。

例如在实现insert方法的时候
if(i>curLen || i<0){ throw new Exception("插入位置不合法!!"); }
后面就不需要再
if (i<=curLen && i>=0)


文外:数据结构可视化:https://www.cs.usfca.edu/~galles/visualization/Algorithms.html 
内容也很全面,暂停(pause)后,可以手动逐步操作(前进、后退),非常方便。



原文地址:https://www.cnblogs.com/mathlin/p/10559601.html