java线性表添加元素的方法_java实现线性表的顺序存储操作

新建一个接口:IList,定义操作:

package com.list;

public interface IList {

public void clear();//清空线性表

public boolean isEmpty();

public int length();//获取元素个数

public Object get(int i) throws Exception;//获取第 i+1 个元素,i从0开始

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类实现IList接口的方法:

package com.list;

public class SqList implements IList {

public Object[] listElem;//线性表存储空间

public int curLength;//线性表当前长度

public SqList(int maxSize) {

curLength = 0;

listElem = new Object[maxSize];

}

@Override

public void clear() {

curLength = 0;

}

@Override

public boolean isEmpty() {

return curLength == 0;

}

@Override

public int length() {

return curLength;

}

@Override

public Object get(int i) throws Exception {

if (curLength == 0) {

throw new Exception("当前线性表为空 --> " + curLength);

}

if (i < 0 || i >= curLength) {

throw new Exception("第" + i + "个元素不存在");

}

return listElem[i];

}

@Override

public void insert(int i, Object x) throws Exception {

if (curLength == listElem.length) {

throw new Exception("顺序表已满");

}

if (i < 0 || i >= listElem.length) {

throw new Exception("插入位置不合法");

}

for (int j = curLength; j > i; j--) {

listElem[j] = listElem[j - 1];

}

listElem[i] = x;

curLength++;

}

@Override

public void remove(int i) throws Exception {

if (i < 0 || i >= curLength) {

throw new Exception("删除位置不合法");

}

for (int j = i; j < curLength - 1; j++) {

listElem[j] = listElem[j + 1];

}

curLength--;

}

@Override

public int indexOf(Object x) {

int j = 0;

while (j < curLength && !listElem[j].equals(x)) {

j++;

}

if (j < curLength) {

return j;

}else {

return -1;

}

}

@Override

public void display() {

for (int j = 0; j < curLength; j++) {

System.err.println(listElem[j]);

}

}

public static void main(String[] args) {

SqList list = new SqList(10);

try {

list.insert(0, 1);

list.insert(0, 2);

} catch (Exception e) {

e.printStackTrace();

}

list.display();

}

}

线性表顺序存储的总结:

优点:

1、无需为表示元素之间的关系而增加额外的存储空间;

2、可以快速的存取表中任一位置的元素。(时间复杂度为O(1))

缺点:

1、插入和删除操作需要移动大量的元素;(时间复杂度为O(N))

2、当线性表长度变化较大时,无法确定存储空间容量;

3、易造成存储空间的“碎片”。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值