Java顺序表的实现

线性表是由n(n>=0)个元素构成的有限序列,通常表示为a0,a1,a2, ...,an-1,它是最简单的数据结构。而顺序表就是顺序存储的线性表,它是用一组地址连续的存储单元依次存放各个数据元素的存储结构。

顺序表的主要操作有清空、判断是否为空、求当前长度、获取某个位置元素、插入、删除、查找元素位置等。其中几项很简单,只有插入、删除可能要思考一下,但也是容易解决的。

代码如下:

public class SqlList{

    public Object[] listElement;
    public int currentLength;

    public SqlList(int maxSize)
    {
        listElement=new Object[maxSize];
        currentLength=0;
    }

    //清空
    public void clear()
    {
        currentLength=0;
    }
    //是否为空
    public boolean isEmpty()
    {
        return currentLength==0;
    }
    //当前长度
    public int length()
    {
        return currentLength;
    }

    //插入
    public void insert(int i,Object x) throws Exception
    {
        if(currentLength==listElement.length)
            new Exception("顺序表已满!");
        if(i<0 || i>currentLength)
        {
            throw new Exception("插入位置不合法!");
        }
        for(int j=currentLength;j>i;j--)
            listElement[j]=listElement[j-1];
        listElement[i]=x;
        currentLength++;
    }
    //删除
    public void remove(int i) throws Exception
    {
        if(i<0 || i>=currentLength)
            throw new Exception("删除位置不合法");
        for(int j=i;j<currentLength-1;j++)
        {
            listElement[j]=listElement[j+1];
        }
        currentLength--;
    }

    //获取某个位置元素
    public Object get(int i) throws Exception
    {
        if(i<0 || i>=currentLength)
        {
            throw new Exception("第" + i + "不存在");
        }
        return listElement[i];
    }
    //查找元素所在位置下标
    public int indexOf(Object x)
    {
        for(int i=0;i<currentLength;i++)
        {
            if(listElement[i].equals(x))
                return i;
        }
        return -1;
    }

    //打印输出
    public void display()
    {
        for(int i=0;i<currentLength;i++)
        {
            System.out.print(listElement[i]+" ");
        }
        System.out.println();
    }

    public static void main(String[] args) throws Exception
    {
        SqlList sqlList=new SqlList(30);
        sqlList.insert(0,5);
        sqlList.insert(1,9);
        sqlList.insert(2,8);
        System.out.print("所有元素:");
        sqlList.display();
        System.out.println("9的下标是:"+sqlList.indexOf(9));
        sqlList.remove(2);
        System.out.print("删除下标为2的元素后: ");
        for(int i=0; i<sqlList.length(); i++)
            System.out.print(sqlList.get(i)+" ");
        System.out.println();
    }
}
可以看到顺序表内部是采用一个一维数组来存储数据元素,并没有什么复杂的东西,多看看就Ok了。若有问题,敬请指正!(凡星逝水2017)

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值