import java.util.Arrays;
public class SequenceList<T> {
// 默认数组长度
private int DEFAULT_SIZE = 16;
// 保存数组长度
private int capacity;
// 用于保存线性表的数组
private Object[] elementData;
// 当前存储数据个数
private int size = 0;
// 以默认长度创建存储数组
public SequenceList() {
elementData = new Object[DEFAULT_SIZE];
capacity = DEFAULT_SIZE;
}
// 存储数组长度不足时,数组拓展
private void ensure(int oldsize) {
if (oldsize > capacity) {
while (capacity < oldsize) {
capacity <<= 1;
}
elementData = Arrays.copyOf(elementData, capacity);
}
}
// 以某元素初始化存储数组
public SequenceList(T elemenT) {
this();
elementData[0] = elemenT;
size++;
}
// 以某元素及指定长度初始化存储数组
public SequenceList(T element, int initsize) {
capacity = initsize;
elementData = new Object[initsize];
elementData[0] = element;
size++;
}
// 获取线性表长度
public int length() {
return size;
}
// 获取线性表是否为空
public boolean empty() {
return size == 0;
}
// 获取指定索引的元素
public T get(int i) {
if (i > size - 1 || i < 0) {
throw new RuntimeException("索引越界");
}
return (T)elementData[i];
}
// 查找线性表中的元素位置
public int contains(T key) {
for (int i = 0; i < size; i++) {
if (elementData[i].equals(key)) {
return i;
}
}
return -1;
}
// 向线性表中添加元素
public void add(T element) {
Insert(element, size);
}
// 想存储数组中指定位置插入元素
public void Insert(T element, int index) {
if (index > size || index < 0) {
throw new IndexOutOfBoundsException("不存在该位置");
}
ensure( size + 1);
System.arraycopy(element, index, element, index + 1, size - index);
elementData[index] = element;
size++;
}
// 删除最后一个元素
public T remove() {
return delete(size - 1);
}
// 删除指定位置元素
public T delete(int index) {
if (index < 0 || index > size - 1) {
throw new IndexOutOfBoundsException("线性表越界");
}
T oldValue = (T)elementData[index];
elementData[index] = null;
int key = size - index - 1;
if (key > 0) {
System.arraycopy(elementData, index + 1, elementData, index, key);
}
return oldValue;
}
// 线性表清空
public void clear() {
Arrays.fill(elementData, null);
}
// 输出
public String toString() {
if (size == 0) {
return null;
} else {
StringBuilder str = new StringBuilder();
str.append("[");
for (int i = 0; i < size; i++) {
str.append(elementData[i] + ",");
}
str.append("]");
return str.toString();
}
}
}
数据结构:线性表的顺序存储--Java实现
最新推荐文章于 2022-03-06 15:16:48 发布