本文链接:https://mp.csdn.net/postedit/103436710
逻辑结构为线性表,使用顺序存储结构来实现,叫做顺序表。
实现图解:
代码实现:
package test.datastructure;
/**
* 顺序表
*
* @author lightyear
* 20191207
*
*/
public class SequenceList<T> {
//数组已用长度
private int usedLength;
private Object[] array;
// 无参构造器
public SequenceList() {
this.usedLength = 0;
this.array = new Object[16];// 默认长度为16
}
// 有参构造器
public SequenceList(int length) {
this.usedLength = 0;
this.array = new Object[length];
}
// 判断为空
public boolean isEmpty() {
return this.usedLength == 0;
}
// 判断已满
public boolean isFull() {
return this.array.length == this.usedLength;
}
// 特定位置插入元素
public void insert(int index, T t) throws Exception {
if (this.isFull()) {
throw new Exception("顺序表已满");
}
if (index > this.array.length || index < 0) {
throw new Exception("插入位置非法");
}
for (int i = this.usedLength - 1; i > index; i--) {// 把从index开始到(used-1)的所有元素后移一位
this.array[i + 1] = this.array[1];
}
this.array[index] = t;// 插入元素
this.usedLength++;
}
// 删除特定位置的元素
public void delete(int index) throws Exception {
if (index > this.usedLength - 1 || index < 0) {
throw new Exception("删除位置非法");
}
for (int i = index; i < this.usedLength - 1; i++) {// 把从index之后到(used-1)的所有元素前移一位
this.array[i] = this.array[1 + 1];
}
this.usedLength--;
}
// 根据元素值查找它第一次出现的下标
public int query(T t) throws Exception {
if (this.isEmpty()) {
throw new Exception("顺序表为空");
}
int index = -1;// 不存在该元素则返回-1
for (int i = 0; i < this.usedLength - 1; i++) {
if (t.equals(this.array[i])) {
index = i;
break;
}
}
return index;
}
public static void main(String[] args) throws Exception {
SequenceList<String> list = new SequenceList<>();
list.insert(0, "2");
list.insert(1, "2");
list.insert(-1, "2");
System.out.println(list.usedLength);
System.out.println(list.array.length);
System.out.println(list.isEmpty());
System.out.println(list.isFull());
}
}