#include<stdio.h> #include<stdlib.h> # define MAXSIZE 1000 # define ERROR -1 typedef int position; typedef struct LNode * PtrToLNode; struct LNode{ int Data[MAXSIZE]; position Last; }; typedef PtrToLNode List; List MakeEmpty()//1.初始化 { List L; L=(List)malloc(sizeof(struct LNode)); L->Last=-1; return L; } position Find(List L,int X)//2.查找 { position i=0; while(i<=L->Last&&L->Data[i]!=X) i++; if(i>L->Last) return ERROR; else return i; } bool Insert(List L,int X,int i) {/*在L的制定位序i前插入一個新元素X;位序i元素的數組位置下標是i-1*/ position j; if(L->Last==MAXSIZE-1) {/*表空間已滿,不能插入*/ printf("表滿,不能插入\n\n"); return false; } if(i<1||i>L->Last+2) {/*檢查插入位序的合法性:是否在1~n+1。n爲當前元素個數,即Last+1*/ printf("位序不合法\n\n"); return false; } for(j=L->Last;j>i-1;j--)//List指向序列最後元素 L->Data[j+1]=L->Data[j];//將位序i及之後的元素順序向後移動 L->Data[i-1]=X;//插入數據 L->Last++;//Last仍指向最後元素 return true; } bool Delete(List L,int i)//刪除 { position j; if(i<1||i>L->Last+1) { printf("位序%d不存在\n\n",i); return false; } for(j=i;j<=L->Last;j++) L->Data[j-1]=L->Data[j]; L->Last--; return true; } void Length(List L)//求表長 { position j; position count=0; for(j=0;j<L->Last+1;j++) count++; printf("表的長度:%d\n\n",count); } void Print(List L)//打印 { position j; printf("數據元素:"); for(j=0;j<L->Last+1;j++) printf("%d ",L->Data[j]); printf("\n\n"); } void Menu()//菜單 { int chose; int X,i; List L; printf("\t線性表的順序存儲實現\n"); printf("1.建立順序表\t2.向順序表插入數據\n3.查找數據\t4.刪除數據\n5.求表長\t6.打印順序表\n7.清屏\t\t8.退出\n"); printf("請輸入您的操做:"); scanf("%d",&chose); switch(chose) { case 1: { L=MakeEmpty(); printf("順序表建立完成\n\n"); break; } case 2: { printf("請輸入您想要插入的數據以及位置: "); scanf("%d%d",&X,&i); Insert(L,X,i); printf("\n\n"); break; } case 3: { printf("請輸入您要查找的數據:"); scanf("%d",&X); Find(L,X); printf("%d元素的位置爲%d\n\n",X,Find(L,X)+1); break; } case 4: { printf("請輸入您想要刪除的下標:"); scanf("%d",&i); Delete(L,i); printf("操做完成\n\n"); break; } case 5: { Length(L); printf("\n\n"); break; } case 6: { Print(L); printf("\n\n"); break; } case 7: { system("cls"); break; } case 8: { exit(0); } default:printf("輸入有誤!\n\n"); } } int main() { while(1) { Menu(); //printf("按Enter鍵繼續...\n"); } return 0; }
對部分代碼的解釋:數組
typedef int position; typedef struct LNode * PtrToLNode; struct LNode{ int Data[MAXSIZE]; position Last; }; typedef PtrToLNode List;
變量Last記錄當前線性表中最後一個元素在數組中的位置,即Last起一個指針(實際是數組下標)的做用,始終指向線性表中最後一個元素。表空時Last=-1。
i | 0 | 1 | ... | i-1 | i | ... | n-1 | ... | MAXSIZE-1 |
Data | a1 | a2 | ... | ai | ai+1 | ... | an | ... |
線性表的順序存儲示意圖因爲LNode是一個包含數組的結構,當咱們實現各類針對順序表的操做時,直接將該結構做爲函數參數傳遞顯然不是個好方法,使用結構指針傳遞效率更高,因此咱們把List定義爲結構指針。這樣,咱們能夠利用List定義線性表L: List L;經過L咱們能夠訪問相應線性表的內容。好比下標爲i的元素能夠經過L-Data[i]訪問,線性表的長度能夠經過L->Last+1獲得。