数据结构:JAVA实现简单的顺序表

本文详细介绍了一个基于Java的顺序表实现,包括清空、判断是否为空、获取长度、获取元素、插入、删除和查找等基本操作,并提供了完整的代码示例。

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

public interface IList {
//置空操作
public void clear();
//判空操作
public boolean isEmpty();
//取表长度
public int length();
//取表元素
public Object get(int i) throws Exception;
//插入操作
public void insert(int i, Object x) throws Exception;
//删除操作
public void remove(int i) throws Exception;
//查找操作
public int Indexof(Object x);
//显示
public void display();
}
顺序表类SqList的代码:
public class SqList implements IList{

public Object[] listElem;//线性表存储空间
private int curlen; //线性表当前长度

//顺序表构造函数,构造一个长度为maxSize的线性表
public SqList(int maxSize){
    curlen = 0;
    listElem = new Object[maxSize];
}

//置空操作
public void clear() {
    curlen = 0;
}

//判断当前长度是否为0,为0即为空表
public boolean isEmpty() {
    return curlen == 0;
}

//取表长度,返回curlen当前长度即可
public int length() {
    return curlen;
}

//取表元素
public Object get(int i) throws Exception {
    //判断 i 是否合法
    if(i > 0 || i > curlen -1)
        throw new Exception("第"+i+"个元素不存在");
    return listElem[i];
}

//插入操作
public void insert(int i, Object x) throws Exception {
    if(curlen == listElem.length)
        throw new Exception("顺序表已经满了");
    if(i < 0 || i > curlen)
        throw new Exception("插入位置不合法");
    //从尾部往前扫
    for(int j = curlen; j > i; j--)
        listElem[j] = listElem[j - 1];
    listElem[i] = x;
    //插入成功后,表长度+1
    curlen++;
}

//删除操作
public void remove(int i) throws Exception {
    if(i < 0 || i > curlen - 1)
        throw new Exception("删除位置不合法");
    //下标移动要出删除的i处
    for(int j = i; j < curlen - 1; j++)
        listElem[j] = listElem[j++];
    curlen--;
}

//查找操作,找到则返回下标,否则返回-1
public int Indexof(Object x) {
    int j = 0;
    //遍历查找
    while(j < curlen && !listElem[j].equals(x))
        j++;
    if(j < curlen)
        return j;
    else 
        return -1;
}

//显示操作
public void display() {
    //遍历线性表
    for(int i = 0; i < curlen; i++)
        System.out.println(listElem[i]);
}

//主函数
public static void main(String[] args) throws Exception{
    //初始化线性表
    SqList mlist = new SqList(10);
    mlist.insert(0, "a");
    mlist.insert(1, "b");
    mlist.insert(2, "c");
    mlist.insert(3, "d");
    mlist.insert(4, "e");
    //mlist.insert(5, 'f');      报错了,类型出错

    int findFlag = mlist.Indexof("e");
    if(findFlag != -1)
        System.out.println("顺序表中第一次出现'e'的位置是:"+ findFlag);
    else 
        System.out.println("顺序表不存在元素'e'");

    mlist.display();
}

}

作者:GoGoCoder
来源:优快云
原文:https://blog.youkuaiyun.com/sinat_20418545/article/details/52346094
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值