什么是順序表
順序表是在計算機內(nèi)存中以數(shù)組的形式保存的線性表授瘦,線性表的順序存儲是指用一組地址連續(xù)的存儲單元近她,依次存儲線性表中的各個元素叉瘩、使得線性表中再邏輯結(jié)構(gòu)上響鈴的數(shù)據(jù)元素存儲在相鄰的物理存儲單元中,即通過數(shù)據(jù)元素物理存儲的相鄰關(guān)系來反映數(shù)據(jù)元素之間邏輯上的相鄰關(guān)系粘捎;
常見的如數(shù)組:
在Java中順序表一般體現(xiàn)為兩種 數(shù)組 與 集合薇缅,數(shù)組是固定長度的順序表,集合是動態(tài)長度的順序表晌端,這里實現(xiàn)動態(tài)長度的順序表捅暴;
順序表的實現(xiàn)(直接上代碼)
類名 | SequenceList |
---|---|
成員方法 | 1.public void clear():清空順序表 2.publicboolean isEmpty():判斷順序表是否為空,是返回true咧纠,否返回false 3.public int length():獲取順序表中元素的個數(shù) 4.public T get(int i):讀取并返回順序表中的第i個元素的值 5.public void insert(T t):往順序表中添加一個元素蓬痒; 6.public void insert(int i,T t):在順序表的第i個元素之前插入一個值為t的數(shù)據(jù)元素。 7.public T remove(int i):刪除并返回順序表中第i個數(shù)據(jù)元素漆羔。 8.public int indexOf(T t):返回順序表中首次出現(xiàn)的指定的數(shù)據(jù)元素的位序號梧奢,若不存在狱掂,則返回-1 |
成員變量 | 1.private T [] eles:存儲元素的數(shù)組 2.private int N:記錄順序表的長度 3. private int modCount : 記錄順序表的操作次數(shù) |
public class SequenceList<T> implements Iterable<T>{
private T[] eles;
private int N;
private int modCount;
public SequenceList(){
// this.eles =(T[]) new Object[1];
this.N = 0;
}
public void clear(){
modCount ++;
for (int i = 0;i<this.N;i++) {
eles[i] = null;
}
this.N = 0;
}
public boolean isEmpty(){
return this.N==0;
}
public int length(){
return this.N;
}
public T get(int index){
if(index<0 || index>this.N){
System.out.println("異常");
return null;
}
return this.eles[index];
}
public void insert(T t){
this.modCount++;
ensureCapacityInternal(this.N+1);
this.eles[this.N++] = t;
}
public void insert(int index,T t){
this.modCount++;
if(index<0|| index>this.N){
System.out.println("異常");
return;
}
ensureCapacityInternal(this.N+1);
for (int i = this.N; i>index; i--) {
this.eles[i]= this.eles[i-1];
}
this.eles[this.N++] = t;
}
public T remove(int index){
this.modCount++;
if(index<=0|| index>this.N){
System.out.println("異常");
return null;
}
T t = eles[index];
for (int i = index; i<this.N-1; i++) {
this.eles[i]= this.eles[i+1];
}
ensureCapacityInternal(--this.N);
return t;
}
private void ensureCapacityInternal(int minCapacity){
if(this.N == 0){
this.eles = (T []) new Object[minCapacity];
}else{
T[] temp = (T []) new Object[minCapacity];
int num = minCapacity;
if(num >this.eles.length){
num =this.eles.length;
}
System.arraycopy(this.eles,0,temp,0,num);
this.eles = temp;
}
}
public int indexOf(T t){
for (int i = 0; i < this.N; i++) {
if(this.eles[i].equals(t)){
return i;
}
}
return -1;
}
@Override
public Iterator<T> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<T>{
private int cur ;
private int num;
public MyIterator(){
this.cur = 0;
this.num = modCount;
}
@Override
public boolean hasNext() {
checkModCount();
return cur< N;
}
@Override
public T next() {
checkModCount();
return eles[cur++];
}
private void checkModCount(){
if(this.num != modCount){
throw new RuntimeException("不合法的操作,在遍歷元素時修改數(shù)據(jù)是不安全的亲轨!");
}
}
}
}