Create a new interface: IList, define the operation:
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();
}
Create a new SqList class to implement the method of the IList interface:
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();
}
}
Summary of linear table sequential storage:
advantage:
1. There is no need to add additional storage space for representing the relationship between elements;
2. You can quickly access elements at any position in the table. (time complexity is O(1))
shortcoming:
1. Insertion and deletion operations require moving a large number of elements; (time complexity is O(N))
2. When the length of the linear table changes greatly, the storage space capacity cannot be determined;
3. It is easy to cause "fragmentation" of storage space.