顺序表练习
图解插入与删除,详见相关内容:顺序存储结构的插入与删除
//顺序表的定义、创建、插入、删除、查找
//定义:结构体中数组、表长
//创建:输入元素,表长++
//插入:判断表是否已满、判断位序合法性
//插入位序k(对应下标k-1)从k-1到length-1元素依次后移,插入元素,表长+1
//删除:判断表是否已空、判断位序合法性
//删除位序k(对应下标k-1),元素赋值给e,从length-1到k依次前移,表长-1
//查找:元素内容,下标从0开始检查元素是否等于当前元素,若等则返回位序(下标+1)
#include<stdio.h>
#define MAXSIZE 10
#define OK 1
#define ERROR 0
typedef int Status;
typedef struct{int data[MAXSIZE];int length;
}SqList;
//初始化
void InitSqList(SqList *L){L->data[MAXSIZE]=0;L->length=0;
}
//创建
void CreateSqList(SqList *L,int n){for (size_t i = 0; i < n; i++){printf("输入第%d个元素:",i+1);scanf("%d",&L->data[i]);L->length++;}
}
//插入
Status InsertElem(SqList *L,int k,int e){int i;//下标//判断表满、位序合法性if (L->length==MAXSIZE || k<1 || k> L->length){return ERROR;}//元素后移for (int i = L->length-1; i >= k-1; i--){L->data[i+1]=L->data[i];}L->data[k-1]=e;L->length++;return OK;
}
//删除
Status DeleteElem(SqList *L,int k){int i;//下标//判断表空、位序合法性if (L->length==0 || k<1 || k> L->length){return ERROR;}//元素前移覆盖要删除的元素for (i = k; i <= L->length-1; i++){L->data[i-1]=L->data[i];}L->length--;return OK;
}
//查找
int LocateElem(SqList *L,int e){int i;//下标for (i = 0; i < L->length; i++){if (L->data[i]==e){return i+1;//返回位序}}return 0;
}
//打印
Status PrintList(SqList *L){//判断表空、位序合法性if (L->length==0){return ERROR;}for (size_t i = 0; i < L->length; i++){printf("%d ",L->data[i]);}return OK;
}
int main(){int n,e,k;SqList L;InitSqList(&L);printf("输入表长:");scanf("%d",&n);CreateSqList(&L,n);PrintList(&L);printf("\n输入插入位序及元素:");scanf("%d%d",&k,&e);InsertElem(&L,k,e);printf("插入元素后:");PrintList(&L);printf("\n输入要删除的元素的位序:");scanf("%d",&k);DeleteElem(&L,k);PrintList(&L);printf("\n输入要查询的元素:");scanf("%d",&e);k=LocateElem(&L,e);printf("所查询的元素位序为:%d",k);return 0;
}