1.線性表:線性表是n個類型相同數據元素的有限序列。其邏輯結構是對於n>0,除第一個元素無直接前驅、最后一個元素無直接后繼外,其余元素均只有一個直接前驅和一個直接后繼,如下圖所示,數據元素具有一對一的關系
記作(a1,a2,a3,···,ai-1,ai,ai+1,···,an)。
2.線性表的特點:
同一性:線性表由同類數據元素構成,每一個ai必須屬於同一類數據類型。
有窮性:線性表由有限個數據元素組成,表的長度就是數據元素的個數。
有序性:線性表相鄰元素之間存在序偶關系<ai,ai+1>。
3.線性表的順序存儲結構:指的是用一組連續的存儲單元一次存儲線性表中的各個元素,使得線性表中在邏輯上相連的元素存儲在連續的物理存儲單元上。通過數據元素物理存儲的連續性來反映數據元素在邏輯上的相鄰關系。采用順序存儲結構的線性表通常叫做順序表。如下圖,是順序存儲結構示意圖:
圖中k表示每一個數據在內存中占k個單元。Loc(a1)為該線性表第一個元素的地址。
4.順序表的相關操作:(在VS2013編譯環境下運行)
SeqList.h:
1 #pragma once 2 #include<stdio.h> 3 #include<assert.h> 4 #define MAXSIZE 100 5 typedef int SDataType; 6 typedef struct SeqList 7 { 8 SDataType array[MAXSIZE]; 9 int count;//保存線性表中的元素個數 10 }SeqList,*pSeqList; 11 12 void InitSeqList(pSeqList pS);//初始化線性表 13 void PushSeqList(pSeqList pS, SDataType data);//插入元素 14 int LengthSeqList(pSeqList pS);//返回線性表中元素的個數 15 int GetKSeqList(pSeqList pS, int k);//返回線性表中的第k個元素的值 16 void InsertSeqList(pSeqList pS, int k,SDataType data);//在第K的位置前插入指定元素data 17 void DelSeqList(pSeqList pS, int k);//刪除在第K個位置的元素 18 void PrintSeqList(pSeqList ps);//打印線性表
SeqList.c:
1 #include"Seqlist.h" 2 void InitSeqList(pSeqList pS) 3 { 4 int i = 0; 5 for (i = 0; i < MAXSIZE; i++) 6 { 7 pS->array[i] = 0; 8 } 9 pS->count = 0; 10 } 11 void PushSeqList(pSeqList pS, SDataType data) 12 { 13 if (pS->count >= MAXSIZE) 14 { 15 printf("線性表已滿,插入操作失敗\n"); 16 return; 17 } 18 pS->array[pS->count] = data; 19 pS->count++; 20 } 21 void PrintSeqList(pSeqList pS) 22 { 23 int i = 0; 24 for (i = 0; i < pS->count; i++) 25 { 26 printf("%d ", pS->array[i]); 27 } 28 } 29 int LengthSeqList(pSeqList pS) 30 { 31 return pS->count; 32 } 33 int GetKSeqList(pSeqList pS, int k) 34 { 35 return pS->array[k-1]; 36 } 37 void InsertSeqList(pSeqList pS, int k, SDataType data) 38 { 39 if (pS->count < k) 40 { 41 printf("插入位置非法\n"); 42 return; 43 } 44 int i = pS->count; 45 if (i < MAXSIZE) 46 { 47 for (i; i>k; i--) 48 { 49 pS->array[i] = pS->array[i - 1]; 50 } 51 pS->array[i] = data; 52 pS->count++; 53 } 54 } 55 void DelSeqList(pSeqList pS, int k) 56 { 57 int i = k; 58 if (k >= pS->count) 59 { 60 printf("刪除位置非法\n"); 61 return 0; 62 } 63 for (i;(i+1) < pS->count; i++) 64 { 65 pS->array[i] = pS->array[i+1]; 66 } 67 pS->count--; 68 }
test.c:(測試函數)
1 #include"Seqlist.h" 2 3 void test() 4 { 5 int k = 0; 6 int k1 = 0; 7 SeqList S; 8 InitSeqList(&S);//初始化線性表 9 PushSeqList(&S, 0); 10 PushSeqList(&S, 1);//插入元素 11 PushSeqList(&S, 2); 12 PushSeqList(&S, 3); 13 PushSeqList(&S, 4); 14 PushSeqList(&S, 5); 15 PrintSeqList(&S);//打印線性表 16 printf("\n"); 17 k = LengthSeqList(&S);//返回線性表中元素的個數 18 printf("線性表中元素的個數為:%d\n", k); 19 k1 = GetKSeqList(&S, 2); 20 printf("線性表中第%d個位置的元素為:%d \n", 2,k1); 21 InsertSeqList(&S, 2, 8); 22 PrintSeqList(&S); 23 printf("\n"); 24 DelSeqList(&S, 2); 25 PrintSeqList(&S); 26 } 27 28 int main() 29 { 30 test(); 31 system("pause"); 32 return; 33 }
運行界面如下圖:
5.對於順序表的插入刪除操作,為保證邏輯上相鄰的元素在物理地址上也相鄰,在插入或刪除一個元素后不得不進行大量的數據移動。因此,在順序表中插入和刪除一個數據元素時,其時間主要花費在移動數據元素上。做一次插入或刪除平均需要移動順序表中一半的元素,當n較大時算法效率低。但對於查找元素來說,順序表很方便。