下面给出线性表的基本实现,包括测试用例,由20年陈姥姥的数据结构的课程开始写起。
#include<stdio.h>
#include<stdlib.h>
/*
List MakeEmpty();//初始化线性表
ElementType FindKth(int K,List L);//查找位序K的值,返回相应的元素
int Find(ElementType X,List L);//在线性表查找第一次出现的位置
void Insert(ElementType X,int i,List L);在位序i前插入X元素
void Delete(int i,List L);//删除指定位序列i的元素
int Length(List L);//返回线性表的长度
*/
#define MAXSIZE 100
#define TRUE 1
#define FALSE -1
typedef struct LNode *List;
typedef int ElementType;
struct LNode{
ElementType Data[MAXSIZE];
int Last;
};
struct LNode L;
List MakeEmpty(){
List PtrL;
PtrL = (List)malloc(sizeof(struct LNode));
PtrL->Last = -1;//设置-1结果
return PtrL;
}
int Find(ElementType X,List PtrL){
int i = 0;
while(i <= PtrL->Last && PtrL->Data[i]!=X)
i++;
if(i>PtrL->Last) return FALSE;
else return i+1;
}
void Insert(ElementType X,int i,List PtrL){
int j;
if(PtrL->Last == MAXSIZE-1){
printf("表满");
return ;
}
if(i<1 || i>PtrL->Last+2){
printf("位置不合法");
return ;
}
for (j=PtrL->Last;j>=i-1;j--)
PtrL->Data[j+1] = PtrL->Data[j];
PtrL->Data[i-1]=X;
PtrL->Last++;
return ;
}
void Delete(int i,List PtrL){
int j;
if(i<1||i>PtrL->Last+1){
printf("不存在第%d个元素",i);
return ;
}
for(j=i;j<=PtrL->Last;j++)
PtrL->Data[j-1] = PtrL->Data[j];
PtrL->Last--;
return ;
}
ElementType FindKth(int K,List PtrL)//查找位序K的值,返回相应的元素
{
if(K<1 || K>PtrL->Last+1){
printf("不存在第%d个位序",K);
return FALSE;
}
return PtrL->Data[K+1];
}
void PrintL(List PtrL){
for(int i = 0;i<=PtrL->Last;i++){
printf(" %d",PtrL->Data[i]);
}
printf("\n");
}
int Length(List PtrL)//返回线性表的长度
{
return PtrL->Last;
}
void Alter(ElementType X,int i,List PtrL){//将第i位置进行值的修改
if(i<1||i>PtrL->Last+1){
printf("不存在第%d个元素",i);
return ;
}
PtrL->Data[i]=X;
}
int main()
{
List L = MakeEmpty();
Insert(1,1,L);
Insert(2,2,L);
Insert(3,3,L);
Insert(4,4,L);
Insert(5,5,L);
Insert(6,6,L); //增加
PrintL(L); //打印
Insert(100,3,L);
PrintL(L);
Delete(2,L);//查找
PrintL(L);
int m = Find(100,L);//查找
if(m!=-1){
printf("The number was found!\n");
}
Alter(200,2,L);
PrintL(L);
return 0;
}