今天复习数据结构,按照疯狂java,自己敲了一遍线性表的顺序存储,为了下次看方便,在这里保留一份。
package mysequence;
import java.util.Arrays;
/**
* @author lirui
* @param <T>
*/
public class SequenceList<T> {
private int DEFAULT_SIZE = 16;
private int capacity;// 保存数组长度。
private Object[] elementData;// 定义数组,用于保存顺序线性表的元素。
private int size = 0;// 保存顺序表中元素的当前个数。
// 以默认长度定义顺序表。
public SequenceList() {
capacity = DEFAULT_SIZE;
elementData = new Object[DEFAULT_SIZE];
}
// 以一个初始化元素创建线性表。
public SequenceList(T element) {
this();
elementData[0] = element;
size++;
}
/*
* 以指定长度的数组来创建线性表。
*
* @param element 指定顺序表中的第一个元素。
*
* @param initSize 指定顺序表的底层数组的长度。
*/
public SequenceList(T element, int initSize) {
capacity = 1;
// 把capacity设为大于initSize的最小的2的n次方。
while (capacity < initSize) {
capacity = capacity << 1;
}
elementData = new Object[capacity];
elementData[0] = element;
size++;
}
// 获得顺序表的长度
public int length() {
return size;
}
// 获取顺序表中索引为i的元素
public T get(int i) {
if (i < 0 || i > size - 1) {
throw new IndexOutOfBoundsException("线性表索引越界");
}
return (T) elementData[i];
}
// 查找顺序表指定元素的索引
public int Locate(T element) {
for (int i = 0; i < size; i++) {
if (element.equals(elementData[i])) {
return i;
}
}
return -1;
}
// 向顺序表中指定位置插入一个元素。
public void insert(T element, int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("线性表索引越界");
}
ensureCapacity(size + 1);
// 把指定元素后移
System.arraycopy(elementData, index, elementData, index + 1, size
- index);
elementData[index] = element;
size++;
}
// 在线性表开始出添加一个元素
public void add(T element) {
insert(element, size);
}
// 删除线性表中指定索引处的元素
public T delete(int index) {
if (index < 0 || index > size - 1) {
throw new IndexOutOfBoundsException("线性表索引越界");
}
T old = (T) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index,
numMoved);
}
// 清空最后一个元素
elementData[--size] = null;
return old;
}
// 删除线性表中的最后一个元素
public T remove() {
return delete(size - 1);
}
// 判断线性表是否为空
public boolean isEmpty() {
return size == 0;
};
// 清空线性表
public void clear() {
Arrays.fill(elementData, null);
size = 0;
}
@Override
public String toString() {
if (size == 0) {
return "[]";
} else {
StringBuffer sbBuffer = new StringBuffer();
sbBuffer.append("[");
for (int i = 0; i < size - 1; i++) {
sbBuffer.append(elementData[i].toString() + " ,");
}
sbBuffer.append(elementData[size - 1].toString());
sbBuffer.append("]");
return sbBuffer.toString();
}
}
private void ensureCapacity(int minCapacity) {
while (minCapacity > capacity) {
capacity = capacity << 2;
}
elementData = Arrays.copyOf(elementData, capacity);
}
public static void main(String[] args) {
SequenceList<String> myList = new SequenceList<>();
myList.add("aaaa");
myList.add("bbbb");
myList.add("cccc");
System.out.println(myList);
myList.insert("dddd", 1);
System.out.println(myList);
myList.delete(2);
System.out.println(myList);
System.out.println("cccc在线性表中的位置"+myList.Locate("cccc"));
}
}