【数据结构】线性表的顺序存储结构:顺序表(Java实现)

本文链接:https://mp.csdn.net/postedit/103436710

逻辑结构为线性表,使用顺序存储结构来实现,叫做顺序表。

实现图解:

代码实现:

package test.datastructure;

/**
 * 顺序表
 *
 * @author lightyear
 * 20191207
 *
 */
public class SequenceList<T> {
    //数组已用长度
    private int usedLength;

    private Object[] array;

    // 无参构造器
    public SequenceList() {
        this.usedLength = 0;
        this.array = new Object[16];// 默认长度为16
    }

    // 有参构造器
    public SequenceList(int length) {
        this.usedLength = 0;
        this.array = new Object[length];
    }

    // 判断为空
    public boolean isEmpty() {
        return this.usedLength == 0;
    }

    // 判断已满
    public boolean isFull() {
        return this.array.length == this.usedLength;
    }

    // 特定位置插入元素
    public void insert(int index, T t) throws Exception {
        if (this.isFull()) {
            throw new Exception("顺序表已满");
        }
        if (index > this.array.length || index < 0) {
            throw new Exception("插入位置非法");
        }
        for (int i = this.usedLength - 1; i > index; i--) {// 把从index开始到(used-1)的所有元素后移一位
            this.array[i + 1] = this.array[1];
        }
        this.array[index] = t;// 插入元素
        this.usedLength++;
    }

    // 删除特定位置的元素
    public void delete(int index) throws Exception {
        if (index > this.usedLength - 1 || index < 0) {
            throw new Exception("删除位置非法");
        }
        for (int i = index; i < this.usedLength - 1; i++) {// 把从index之后到(used-1)的所有元素前移一位
            this.array[i] = this.array[1 + 1];
        }
        this.usedLength--;
    }

    // 根据元素值查找它第一次出现的下标
    public int query(T t) throws Exception {
        if (this.isEmpty()) {
            throw new Exception("顺序表为空");
        }
        int index = -1;// 不存在该元素则返回-1
        for (int i = 0; i < this.usedLength - 1; i++) {
            if (t.equals(this.array[i])) {
                index = i;
                break;
            }
        }
        return index;
    }

    public static void main(String[] args) throws Exception {
        SequenceList<String> list = new SequenceList<>();
        list.insert(0, "2");
        list.insert(1, "2");
        list.insert(-1, "2");
        System.out.println(list.usedLength);
        System.out.println(list.array.length);
        System.out.println(list.isEmpty());
        System.out.println(list.isFull());
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值