数据结构-顺序表

本文详细介绍Java中顺序表的实现方式,包括插入、查找、删除等基本操作,并提供完整代码示例。

文章目录

简介

顺序表应该是最简单的数据结构了吧,顺序表逻辑上是一个线性表,同时在物理存储上也是线性存储的结构,同样相对应的有一个链表,链表逻辑上线性存储上不满足线性的存储结构。java 数组就是一个顺序表,由于 java 用不了 C 和 C++ 的指针,所以下面只能用数组来替代了

顺序表优势在于查找,劣势在于插入和删除,因为查找直接可以找到值,插入和删除则需要通过遍历重新调整表结构

Java 实现

逻辑思路:

顺序表的插入会将数据一个个的后移,顺序表删除会把数据一个个前移,顺序表依据下标查询会很简单,但是依据值查询还是逃不了遍历,其就是一个数组结构

代码实现:

// 顺序表
public class SequenceList {
    // 顺序表节点
    private int[] arr;
    // 顺序表默认长度
    private static final int DEFAULT_CAPACITY = 10;
    // 顺序表中元素个数
    private int count;
    
    // 初始化顺序表存储(未指明大小)
    public SequenceList() {
        count = 0;
        arr = new int[DEFAULT_CAPACITY];
    }
    // 初始化顺序表存储(指明大小)
    public SequenceList(int capacity) throws Exception {
        if (capacity < 0)
            throw new Exception("顺序表大小不允许小于0!");
        count = 0;
        arr = new int[capacity];
    }
    
    // 顺序表尾部新增
    public void add(int e) throws Exception {
        if (count >= arr.length)
            throw new Exception("顺序表存满,不允许再存入!");
        arr[count++] = e;
    }
    
    // 顺序表根据下标查找值
    public int searchByValue(int index) throws Exception {
        if (index < 0)
            throw new Exception("下标不允许小于0!");
        if (index >= count)
            throw new Exception("下标超出了,没有数据存入!");
        return arr[index];
    }
    // 顺序表根据值查找下标
    public int searchByIndex(int value) {
        for (int i = 0; i < count; i++)
            if (arr[i] == value)
                return i;
        return -1;
    }
    
    // 顺序表依据下标插入,其他数据后移
    public void insert(int index, int e) throws Exception {
        if (index < 0)
            throw new Exception("下标不允许小于0!");
        if (index >= count)
            throw new Exception("下标超出了,没有数据存入!");
        if (count >= arr.length)
            throw new Exception("顺序表存满,不允许再存入!");
        for (int i = count - 2; i >= index; i--)
            arr[i+1] = arr[i];
        arr[index] = e;
    }
    
    // 顺序表依据下标删除
    public int delete(int index) throws Exception {
        if (index < 0)
            throw new Exception("下标不允许小于0!");
        if (index >= count)
            throw new Exception("下标超出了,没有数据存入!");
        int e = arr[index];
        for (int i = index + 1; i <= count - 1; i++)
            arr[i-1] = arr[i];
        count--;
        return e;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

abcnull

您的打赏是我创作的动力之一

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值