//順序表 Sequential List
#include<stdio.h>
#include<string.h>
#define MAXLEN 100 //定義順序表的最大長度
typedef struct //定義節點類型
{
char key[10]; //節點的關鍵字
char name[20];
int age;
}DATA;
typedef struct //定義順序表結構
{
DATA ListData[MAXLEN+1]; //儲存順序表的結構數組,從下標1開始記錄資料節點,下標0位置不使用
int ListLen; //順序表已存節點數量
}SLType;
void SLInit(SLType *SL) //初始化順序表
{
SL->ListLen=0; //初始化為空白表,沒有清空表,如表中有資料可被覆蓋
}
int SLLength(SLType *SL) //返回順序表的元素數量
{
return SL->ListLen;
}
int SLInsert(SLType *SL,int n,DATA data) //插入節點
{
int i;
if(SL->ListLen>=MAXLEN)
{
printf("順序表已滿,不能插入節點!\n");
return 0;
}
if(n<1||n>SL->ListLen-1)
{
printf("插入元素序號錯誤,不能插入!\n");
return 0;
}
for(i=SL->ListLen;i>=n;i--) //順序表節點後移
{
SL->ListData[i+1]=SL->ListData[i];
}
SL->ListData[i]=data;
SL->ListLen++;
return 1;
}
int SLAdd(SLType *SL,DATA data) //追加節點
{
if(SL->ListLen>=MAXLEN)
{
printf("順序表已滿,不能插入節點!\n");
return 0;
}
SL->ListData[++SL->ListLen]=data;
return 1;
}
int SLDelete(SLType *SL,int n) //刪除節點
{
int i;
if(n<1||n>SL->ListLen)
{
printf("刪除節點序號錯誤,不能刪除節點!\n");
return 0;
}
for(i=n;i<SL->ListLen;i++)
{
SL->ListData[i]=SL->ListData[i+1];
}
SL->ListLen--;
return 1;
}
DATA *SLFindByNum(SLType *SL,int n) //按序號尋找節點
{
if(n<1||n>SL->ListLen+1)
{
printf("節點序號錯誤,不能返回節點!\n");
return NULL;
}
return &(SL->ListData[n]);
}
int SLFindByCont(SLType *SL,char *key) //按關鍵字尋找節點
{
int i;
for(i=1;i<SL->ListLen;i++)
{
if(strcmp(SL->ListData[i].key,key)==0)
{
return 1;
}
}
return 0;
}
int SLAll(SLType *SL)
{
int i;
for(i=1;i<=SL->ListLen;i++)
{
printf("(%s,%s,%d)\n",SL->ListData[i].key,SL->ListData[i].name,SL->ListData[i].age);
}
return 0;
}
int main()
{
int i;
SLType SL;
DATA data;
DATA *pdata;
char key[10];
printf("順序表操作示範!\n");
SLInit(&SL);
printf("順序表初始化完成!\n");
do{
printf("輸入添加的節點(學號 姓名 年齡):");
fflush(stdin);
scanf("%s%s%d",&data.key,&data.name,&data.age);
if(data.age)
{
if(!SLAdd(&SL,data))
{
break;
}
}
else
{
break;
}
}while(1);
printf("\n順序表中的節點順序為:\n");
SLAll(&SL);
fflush(stdin);
printf("\n要取出節點的序號:");
scanf("%d",&i);
pdata=SLFindByNum(&SL,i);
if(pdata)
{
printf("第%d個節點為:(%s,%s,%d)\n",i,pdata->key,pdata->name,pdata->age);
}
fflush(stdin);
printf("\n輸入要尋找的關鍵字:");
scanf("%s",key);
i=SLFindByCont(&SL,key);
pdata=SLFindByNum(&SL,i);
if(pdata)
{
printf("第%d個節點為:(%s,%s,%d)\n",i,pdata->key,pdata->name,pdata->age);
}
printf("\n輸入要刪除的節點序號:");
scanf("%d",&i);
SLDelete(&SL,i);
SLAll(&SL);
getchar();
return 0;
}