线性表的严格定义:
具有相同特性的数据元素的一个有序序列。
线性表的特征:
- 所有数据元素类型相同;
- 由有限个数据元素构成;
- 其中的数据元素与位置相关,即每个数据元素有唯一的序号(或索引)。
顺序表
public class SqList<E> {
private E[] data;
private int size;
private int capacity;
private static final int INITCAPACITY = 10;
public SqList() {
data = (E[]) new Object[INITCAPACITY];
capacity = data.length;
size = 0;
}
private void updateCapacity(int newCapacity) {
E[] newData = (E[]) new Object[newCapacity];
if (size >= 0) System.arraycopy(data, 0, newData, 0, size);
capacity = newData.length;
data = newData;
}
public void createList(E[] array) {
for (size = 0; size < array.length; size++) {
if (size == capacity)
updateCapacity(2 * capacity);
data[size] = array[size];
}
}
public void add(E e) {
if (size == capacity)
updateCapacity(2 * capacity);
data[size++] = e;
}
public int getSize() {
return size;
}
public void setSize(int length) {
if (length < 0 || length > size)
throw new IllegalArgumentException("设置长度length不在有效范围内!");
size = length;
}
public E getElement(int index) {
if (index < 0 || index >= size)
throw new IllegalArgumentException("查找位置index不在有效范围内");
return data[index];
}
public void setElement(int index, E e) {
if (index < 0 || index >= size)
throw new IllegalArgumentException("设置位置index不在有效范围内");
data[index] = e;
}
public int getIndex(E e) {
for (int i = 0; i < size; i++)
if (data[i].equals(e))
return i;
return -1;
}
public void swap(int index1, int index2) {
E temp = data[index1];
data[index1] = data[index2];
data[index2] = temp;
}
public void insert(int index, E e) {
if (index < 0 || index > size)
throw new IllegalArgumentException("插入位置index不在有效范围内");
if (size == capacity)
updateCapacity(2 * capacity);
for (int i = size++; i > index; i--)
data[i] = data[i - 1];
data[index] = e;
}
public void delete(int index) {
if (index < 0 || index >= size)
throw new IllegalArgumentException("删除位置index不在有效范围内");
for (int i = index; index < --size; index++)
data[i] = data[i + 1];
if (capacity > INITCAPACITY && size <= capacity / 4)
updateCapacity(capacity / 2);
}
@Override
public String toString() {
StringBuilder str = new StringBuilder("[");
for (int i = 0; i < size; i++)
if (i == 0)
str.append(data[i]);
else
str.append(", ").append(data[i]);
return str.append("]").toString();
}
}