java实现顺序表

package com.demo.ch02;

import java.util.Objects;

/**
 * Created by hp on 2016/11/14.
 */
public class SqList implements IList{
    Object[] listElem;//线性表存储空间
    int curLen;//线性表的当前长度

    SqList(int maxSize) {
        curLen = 0;//置顺序表的当前长度为0
        listElem = new Object[maxSize];//为顺序表分配maxSize个存储单元

    }

    //将一个已经存在的线性表置成空表
    @Override
    public void clear() {
        curLen = 0;//置顺序表的当前长度为0
    }

    //判断线性表中的数据元素个数是否为0,若为0反回true,否则反回false
    @Override
    public boolean isEmpty() {
        return curLen == 0;
    }
    //求线性表中的元素个数并返回其值
    @Override
    public int length() {
        return curLen;//返回顺序表的当前长度
    }
    @Override
    public Object get(int i) throws Exception {
        if (i < 0 || i >= curLen) {
            throw new Exception("" + i + "个元素不存在");
        }
        return listElem[i];
    }

    //插入
    @Override
    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;
        curLen++;
    }

    //删除
    @Override
    public void remove(int i) throws Exception {
        if (i < 0 || i > curLen) {
            throw new Exception("删除位置不合法");
        }
        for (int j = i; j < curLen - 1; j++) {
            listElem[j] = listElem[j + 1];//被删除元素及其之后的数据元素左移一个存储位置
        }
        curLen--;
    }
    @Override
    public int indexOf(Object x) {
        int j = 0;
        while (j < curLen && !listElem[j].equals(x)) {
            j++;
        }
        if (j < curLen) {
            return j;
        }
        return -1;
    }
    @Override
    public void display() {
        for (int i = 0; i < curLen; i++) {
            System.out.print(listElem[i] + " ");

        }
        System.out.println();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值