顺序表的优点:⑴无需为表示表中元素之间的逻辑关系而增加额外的存储空间;
⑵随机存取:可以快速地存取表中任一位置的元素顺序表的缺点:⑴插入和删除操作需要移动大量元素;
⑵表的容量难以确定,表的容量难以扩充;
⑶造成存储空间的碎片。 自己手动写的顺序表代码: import java.util.NoSuchElementException; public class SquenceList<Type> { private static final int DEFAULT_CAPACITY=10; private Type[] elements; private int size; public SquenceList(){ size = DEFAULT_CAPACITY; elements = (Type[])new Object[DEFAULT_CAPACITY]; } public SquenceList(int size){ this.size = size; elements = (Type[]) new Object[size]; } public int getSize(){ return this.size; } public void clear(){ this.size=0; elements = (Type[])new Object[this.size]; } public boolean isEmpty(){ return size==0; } public Type getByIndex(int index){ if (index<0||index>=size){ throw new ArrayIndexOutOfBoundsException(); } else{ return elements[index]; } } public int getIndex(Type type) { for (int i = 0; i < size; i++) { if (elements[i].equals(type)) {//Searching by traversal temporarily return i; } } throw new NoSuchElementException(); } public void ensureCapacity(int size){ if(size<=this.size){ return; } else { Type[] old = elements; elements = (Type[]) new Object[size]; for (int i = 0;i<this.size;i++){ elements[i]=old[i]; } } } public void trimToSize() { ensureCapacity(size); } public void add(int index, Type x){ if( index<0 || index>size ) throw new ArrayIndexOutOfBoundsException(); if(elements.length==size) ensureCapacity(size*2+1); for (int i=size; i>index; i--) elements[i]=elements[i-1]; elements[index]=x; size++; } public boolean add(Type x){ add(size, x); return true; }public void add(int index, Type x){
if(index<0 || index>size )
throw new ArrayIndexOutOfBoundsException();
if(elements.length==size)
ensureCapacity(size*2+1);
for(int i=size; i>index; i--)
elements[i]=elements[i-1];
elements[index]=x;
size++;
}
public boolean add(Type x){
add(size,x);
return true;
}
} 对于插入数据操作的分析:假设在长度为n 的线性表中任意一个位置插入一个元素的概率是相等的,则所需移动元素次数的期望值为n/2 删除一个元素时为(n-1)/2
09-16
734