Java代码实现线性表顺序存储

该博客详细介绍了如何使用ElemType数据结构实现顺序表,包括初始化、清空、判断是否为空、获取长度、获取指定位置元素、查找元素位置、插入元素和删除元素等操作。内容覆盖了数据结构的基础知识和实际应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ElemType

ElemType类型要根据实际情况而定

public class ElemType {

    private String name;
    private Object data;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

顺序表实现

public class SqList {

    private int maxLength;//最大的长度
    private int currLength;//当前的长度
    private ElemType[] elemList;

    /*初始化 initSqList*/
    public SqList(int maxSize) {
        this.currLength = 0;
        this.maxLength = maxSize;
        elemList = new ElemType[maxSize];
    }

    /*清空线性表*/
    public void clear() {
        this.currLength = 0;//当前长度置为0
    }

    /*返回线性表是否为空*/
    public boolean isEmpty() {
        return this.currLength == 0;//当前长度是否0
    }

    /*返回线性表的长度*/
    public int getLength() {
        return this.currLength;//返回当前长度
    }

    /*返回指定第i个元素*/
    public ElemType getElem(int i) throws Exception {
        //线性表长度为0 或 index为负数 或 大于当前下标
        if (elemList.length == 0 || i < 0 || i > currLength)
            throw new Exception("ERROR");
        return elemList[i];
    }

    /*返回指点元素的位置*/
    public int getIndex(ElemType x) throws Exception {
        for (int i = 0; i < elemList.length; i++) { //遍历比较
            if (x.toString().equals(elemList[i].toString())) {
                return i;
            }
        }
        return -1;//不存在返回-1
    }

    /*在线性表第i个元素前插入x*/
    public void insert(int i, ElemType x) throws Exception {
        if (currLength == maxLength) //线性表是否已满
            throw new Exception("ERROR");
        if (i < 0 || i > currLength) //插入下标小于0或者大于表的长度
            throw new Exception("ERROR");
        for (int j = currLength - 1; j >= i; j--) {  //将下标为i后的元素后移
            elemList[j + 1] = elemList[j];
        }
        elemList[i - 1] = x; //赋值
        currLength++; //长度加1
    }

    /*删除线性表中的第i个数据元素*/
    public void remove(int i) throws Exception {
        if (i < 0 || i > currLength) //删除下标小于0或大于表的长度
            throw new Exception("ERROR");
        for (int j = currLength - 1; j > currLength - 1; j--) { //将下标为i后的元素前移
            elemList[j] = elemList[j + 1];
        }
        currLength--; //长度减1
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值