C语言数据结构顺序表基本操作中创建插入删除代码

#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;
}

大家一起学习

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kevinfkq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值