数据结构顺序表增删查改

定义顺序表结构

#define MAXSIZE 100

typedef struct {
    int date[MAXSIZE];  // 存放整数的数组
    int Length;         // 当前顺序表中元素的个数
} Seqlist;

创建顺序表


Seqlist* CreatSeqlist() { // 创建顺序表
    Seqlist* p = (Seqlist*)malloc(sizeof(Seqlist));
    if (p == NULL) {
        printf("内存分配失败!\n");
        return NULL;
    }
    p->Length = 0;
    return p;
}

指定位置插入数据

int InsertSeqlist(Seqlist* p, int date, int pos)
{ // 向顺序表插入元素
	if (pos < 0 || pos > p->Length)
	{
		printf("插入位置不合法!\n");
		printf("插入失败!\n");
		return -1;
	}
	if (p->Length >= MAXSIZE)
	{
		printf("顺序表已满!\n");
		printf("插入失败!\n");
		return -1;
	}
	for (int i = p->Length - 1; i >= pos; i--)
	{
		p->date[i + 1] = p->date[i];
	}
	p->date[pos] = date;
	p->Length++;
	printf("插入成功!\n");
	return 0;
}

查找指定元素

int findSeqlist(Seqlist* p, int date) { // 查找顺序表中的元素,返回元素的位置,若不存在,返回-1
	for (int i = 0; i < p->Length; i++) {
		if (p->date[i] == date) {
			return i;
		}
	}
	return -1; // 元素不存在
}

删除指定位置数据

// 删除顺序表中的元素,pos为元素的位置
int DeleteSeqlist(Seqlist* p, int pos) {
	if (pos < 0 || pos >= p->Length) {
		printf("删除位置不合法!\n");
		printf("删除失败!\n");
		return -1;
	}
	for (int i = pos; i < p->Length - 1; i++) {
		p->date[i] = p->date[i + 1];
	}
	p->Length--;
	printf("删除成功!\n");
	return 0;
}

修改指定位置数据

//修改指定位置数据
int ModifySeqlist(Seqlist* p, int date, int pos) {
	if (pos < 0 || pos >= p->Length) {
		printf("修改位置不合法!\n");
		printf("修改失败!\n");
		return -1;
	}
	p->date[pos] = date;
	printf("修改成功!\n");
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值