順序表結構實現
順序表就是按照順序存儲方式存儲的線性表,該線性表的結點按照邏輯次序放在計算機的一組連續的存儲單元中。
順序表是依次存放的,只要知道了該順序表的首地址及每個數據元素所佔用的存儲長度,那麼就很容易計算出任何一個數據元素的位置。
實體類
public class DATA {
private String key;
private String name;
private int age;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
順序表類
public class SLType {
static final int MAXLEN = 100;
DATA[] ListData = new DATA[MAXLEN];
int ListLen;
// 創建一個順序表
void SLInit(SLType SL){
SL.ListLen = 0;
}
// 計算順序表長度
int SLLength(SLType SL){
return (SL.ListLen);
}
// 插入結點
// 插入結點就是在線性表L的第i個位置插入一個新的結點,使得其後的結點編號一次加1。插入一個結點後線性表L的長度變爲n+1。
int SLInsert(SLType SL,int n,DATA data){
int i;
if(SL.ListLen>=MAXLEN){
System.out.print("順序表已滿,不能插入結點!");
return 0; // 返回0表示插入不成功。
}
if(n<1||n>SL.ListLen+1){
System.out.println("插入元素序號錯誤,不能插入元素!");
return 0;
}
if(SL.ListLen>0){
for(i=SL.ListLen;i>=(n-1);i--){
SL.ListData[i+1] = SL.ListData[i];
}
}
SL.ListData[n-1] = data;
SL.ListLen++;
return 1;
}
// 追加結點
// 該方法可以看做是插入結點的一種特殊形式,相當於在順序表的結尾加一個結點,相對插入結點簡單,不必移動大量結點。
int SLAdd(SLType SL,DATA data){
if (SL.ListLen>=MAXLEN) {
System.out.println("SL = " + "數組已經達到最大長度無法添加!");
return 0;
}
SL.ListData[SL.ListLen] = data;
SL.ListLen++;
return 1;
}
// 刪除結點
// 刪除結點既刪除線性表L中的第i個結點,使其後的所有編號依次減1;刪除結點後線性表的長度會變爲n-1
int SLDelete(SLType SL,int n){
int i;
if(n<1||n>SL.ListLen){
System.out.println("刪除結點序號錯誤,不能刪除結點!");
return 0;
}
for (i = n ;i<=SL.ListLen;i++){
SL.ListData[i-1] = SL.ListData[i];
}
SL.ListLen--;
return 1;
}
// 查找結點
// 對於一個順序表 序號就是其在數組中的位置 從0開始 查找某個節點就把要查找的數字減一
DATA SLFindByNum(int n){
if(n<1||n>this.ListLen){
System.out.println("查找錯誤請從新查找!");
return null;
}
return this.ListData[n-1];
}
// 關鍵字查找
// 按照關鍵字查找結點。
DATA SLFindByCont(String key){
int i;
for(i=0;i<this.ListLen;i++){
if(this.ListData[i].getKey().equals(key)){
return this.ListData[i];
}
}
return null ;
}
// 顯示所有節點
// 顯示所有節點數據並不是一個數據結構基本的運算,因爲其可以簡單地逐個引用節點來實現。
void SLAll(){
int i ;
for (i=0;i<this.ListLen;i++) {
System.out.println("key:" + ListData[i].getKey()+"--name:"+ListData[i].getName()+"--age:"+ListData[i].getAge());
}
}
}
測試main函數
// 測試方法
public static void main(String[] args) {
SLType slType = new SLType();
DATA data = new DATA();
data.setAge(12);
data.setKey("5545");
data.setName("sa");
DATA data1 = new DATA();
data1.setAge(123);
data1.setKey("1111");
data1.setName("222");
slType.SLInsert(slType,1,data); // 添加
slType.SLAdd(slType,data1); // 追加
// slType.SLDelete(slType,1); // 刪除
// DATA dd = slType.SLFindByNum(1);
// DATA dd = slType.SLFindByCont("5545");
slType.SLAll();
System.out.println(slType.ListLen);
//System.out.println(slType.ListData[0].name);ListData[i]
// System.out.println(slType.ListData[1].name);
}
缺點
在插入或者刪除結點時,往往需要移動大量數據。
如果表比較大,有時比較難分配足夠的連續空間,往往導致內存分配失敗,而無法存儲。