在上一篇博文——線性表接口的實現_Java中,我們實現了線性表的接口,今天讓我們來實現線性表的順序存儲結構——順序表類。
首先讓我們來看下順序表的定義:
線性表的順序存儲是用一組連續的內存單元依次存放線性表的數據元素,元素在內存的物理存儲次序與它們在線性表中的邏輯次序相同,即元素ai與其直接前驅ai-1及直接後繼ai+1的存儲位置相鄰。順序存儲的線性表也成爲順序表(sequential list)。
順序表類SeqList提供線性表基於順序存儲結構的一種實現,它有兩個私有成員變量table和n,table是一個存放元素的對象數組;n爲線性表長度,n≤table.length。SeqList聲明如下,它實現了線性表的接口LList。
package dataStructure.linearList;
import dataStructure.linearList.LList;
public class SeqList<E> implements LList<E> //順序表類,實現線性表接口
{
private Object[] table; //對象數組,私有成員
private int n; //順序表長度
public SeqList(int capacity) //構造方法,創建置頂容量的空表
{
this.table = new Object[Math.abs(capacity)];
this.n = 0;
}
public SeqList() //指定空表的默認容量
{
this(16);
}
public boolean isEmpty() //判斷順序表是否爲空,若空返回true
{
return this.n == 0;
}
public int length() //返回順序表長度
{
return this.n;
}
public E get(int index) //返回index(初值爲0)位置的對象,若序號無效,返回null
{
if(index>=0 && index < this.n)
{
return (E)this.table[index];
}
return null;
}
public E set(int index,E element) //設置index位置的對象爲element,若操作成功,放回原對象,否則返回null
{
if(index >= 0 && index < this.n && element != null)
{
E old =(E)this.table[index];
this.table[index] = element;
return old;
}
return null;
}
public boolean add(int index,E element) //在index位置插入element對象,若操作成功返回true,不能插入null
{
if(element == null) //不能插入null
{
return false;
}
if(this.n == table.length) //若數組滿,則需要擴充順序表容量
{
Object[] temp = this.table;
this.table = new Object[temp.length*2]; //重新申請一個容量更大的數組
for(int i = 0;i < temp.length;i++)
{
this.table[i] = temp[i];
}
}
if(index < 0) //下標容錯
{
index = 0;
}
if(index > this.n)
{
index =this.n;
}
for(int j = this.n-1;j >= index;j--) //元素後移,平均移動n/2
{
this.table[j+1] = this.table[j];
}
this.table[index] = element;
this.n++;
return true;
}
public boolean add(E element) //在順序表最後插入element對象
{
return add(this.n,element);
}
public E remove(int index) //移去index位置的對象,若操作成功,則返回被移去的對象,否者返回null
{
if(this.n != 0 && index >= 0 && index < this.n)
{
E old = (E)this.table[index];
for(int j = index;j < this.n-1;j++) //元素前移,平均移動n/2
{
this.table[j] = this.table[j + 1];
}
this.table[this.n - 1] = null;
this.n--;
return old;
}
return null;
}
public void clear() //清空順序表
{
if(this.n != 0)
{
for(int i = 0;i < this.n;i++)
{
this.table[i] = null;
}
this.n=0;
}
}
public String toString() //返回顯示所有元素的字符串,形式爲(,)
{
String str = "(";
if(this.n != 0)
{
for(int i = 0;i < this.n - 1;i++)
{
str += this.table[i].toString()+",";
}
str += this.table[this.n - 1].toString();
}
return str + ")";
}
}
順序表是一種隨即存取結構,存取任何一個元素的get()、set()方法的時間複雜度是O(1)。
對順序表進行插入或刪除操作是,算法所花費的時間主要用於移動元素。在等概率情況下,插入一個元素平均需要移動一半的元素,時間複雜度爲O(n)。同裏,刪除一個元素的時間複雜度亦爲O(n)。
綜上所述,順序表具有下列特點:
①:元素的物理存儲順序直接反映表中元素的邏輯順序,可以隨機存取元素。
②:插入和刪除的操作效率很低。每插入或刪除一個元素,可能需要移動大量元素,其平均移動次數是順序表長度的一半。再者,數組容量不可更改,存在因容量小造成數據溢出,或因容量過大造成內存資源浪費的問題。解決數據溢出的方法是,申請另一個更大容量的數組,並進行數組元素複製,但插入操作效率很低。