#include<stdio.h>//standard input output.header,意为标准输入输出文件。我们通常使用的scanf函数和printf函数,都是依靠该头文件的声明才得以正常使用。
#include<stdlib.h>//standard library标准库头文件, 包含了C语言的一些常用库函数。如动态内存相关的malloc, realloc,zalloc,calloc,free等。
#include<time.h>//是C/C++中的日期和时间头文件。用于需要时间方面的函数。
#define OK 1//宏定义,就是定义ok=1,当后面调用ok的时候,ok就相当于1;
#define ERROR -1//同上
#define LISTSIZEMAX 10//定义顺序表最大长度
#define LISTSIZE 5//初始分配量
typedef int ElemType;
typedef struct {
ElemType *elem;
int length;
int size;
} List;//结构体
//初始化
int CreatList(List *L) {
L->elem = (ElemType*)malloc(sizeof(ElemType)*LISTSIZE);
if(!(L->elem)) {
return ERROR;
}
L->length = 0;
L->size=LISTSIZEMAX;
return OK;
}
//打印
int PrintfList(List *L) {
if(L->length==0) {
printf("顺序表为空!");
return ERROR;
}
int i;
for(i=0; i<L->length; i++) {
printf("%d ",L->elem[i]);
}
printf("\n");
}
//添加元素
void AddListDate(List *L,int n) {
int i;
srand(time(0));
for(i=0; i<n; i++) {
L->elem[i]=rand()%10;
L->length++;
}
PrintfList(L);
}
//插入元素
int ListInsert(List *L,int i,ElemType e) {
int j,newsize;
if(i<1||i>L->length+1)
return ERROR;
if(L->length>=L->size) {
ElemType *newbase;
newsize=(L->size+LISTSIZEMAX)*sizeof(ElemType);//(L.size+LISTSIZEMAX)个ElemType 空间
newbase=(ElemType*)realloc(L->elem,newsize);//指针名=(数据类型*)realloc(要改变内存大小的指针名,新的大小)。
if(!(newsize))
return ERROR;
L->elem=newbase;
L->size+=LISTSIZEMAX;
}
for(j=L->length-1; i-1<=j; j--)
L->elem[j+1]=L->elem[j];
L->elem[i-1]=e;
L->length++;
return OK;
}
//删除元素
int ListDelete(List*L,int i,int &e1){
int j;
if((i<1)||(i>L->length))
return ERROR;
e1=L->elem[i-1];
for(j=i;L->length-1>=j;j++)
L->elem[j-1]=L->elem[j];
L->length--;
return OK;
}
int main(void) {
//初始化
int n;
printf("请输入顺序表初始化数据个数:");
scanf("%d",&n);
List L;
CreatList(&L);
AddListDate(&L,n);
PrintfList(&L);
//插入
int i;
ElemType e;
printf("请输入顺序表插入位置:");
scanf("%d",&i,&e);
printf("请输入顺序表插入数据:");
scanf("%d",&e);
ListInsert(&L,i,e);
PrintfList(&L);
//删除
int j,e1;
printf("请输入顺序表删除位置:");
scanf("%d",&j);
ListDelete(&L,j,e1);
printf("删除数据为:%d\n",e1);
PrintfList(&L);
return 0;
}
大家一起学习