c语言 顺序表的基本操作(创建、初始化、赋值、插入、删除、查询、替换、输出)

c语言 顺序表的基本操作(创建、初始化、赋值、插入、删除、查询、替换、输出)

1、创建、申请空间

2、初始化、顺序表数据结构大小、长度

3、赋值、顺序表数据结构赋值

4、插入、在指定位置插入数据,后续数据循环后移,长度增加,空间大小增加或者不变

5、删除、删除指定位置的数据,后续数据循环前移,长度减小、空间大小不变

6、查询、查看指定数据是否在顺序表结构中

7、替换、将顺序表结构中指定数值替换为另外的数值

8、输出、输出顺序表结构中存储的数据(根据长度大小输出)

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#define Size 5
//显示日期、时间、文件信息
void xinxi()
{

	printf("Date : %s\n", __DATE__);
	printf("Time : %s\n", __TIME__);
	printf("File : %s\n", __FILE__);
	printf("Line : %d\n", __LINE__);
	printf("\n***以下是程序部分***\n\n");
	
}
//定义顺序表结构
typedef struct Table
{
	int *head;//类似于数组指针
	int length;//数据长度
	int size;//机构大小
}table;
//初始化顺序表结构
table initcreact()
{
	table t;
	if ((t.head = (int *)malloc(Size*sizeof(int))) == NULL)
	{
		printf("申请存储空间失败!");
			exit(1);
	}
	t.length = 0;//初始化长度为 0
	t.size = Size;//结构大小
	return t;
}
//结构赋值
table fuzhi(table t)
{
	int i;
	for (i = 0; i < t.size; i++)
	{
		t.head[i] = i + 1;
		t.length++;//长度随赋值情况增加
	}
	return t;
}
//输出结构存储情况
table prt(table t)
{
	printf("存储的数据如下:\n");
	for (int i = 0; i < t.length; i++)
		printf("%d ", t.head[i]);
	printf("\n");
	return t;
}
//插入数据
table insert(table t,int elme,int add)
{
	if (t.length == t.size)//如果数据结构已满,增加存储空间
		t.head= (int *)realloc(t.head, (t.size + 1) * sizeof(int));
	if (t.head == NULL)
	{
		printf("申请存储空间失败!\n");
		exit(1);
	}
	else t.size++;//空间大小增加
	int i = t.size;
	for (; i >= elme-1; i--)//数据循环后移
		t.head[i] = t.head[i - 1];
	t.head[elme-1] = add;//指定位置插入数据,赋值
	t.length++;//长度增加
	return t;
}
//删除指定数据
table deleter(table t, int elme)
{
	int i = elme-1;
	for (; i <= t.size; i++)
		t.head[i] = t.head[i +1];
	t.head[i] = 0;
	t.length--;
	return t;
}
//查询指定数据,返回在数据结构中的位置
int select(table t, int elme)
{
	int i;
	for (i = 0; i <= t.length; i++)
	{
		if (t.head[i] == elme)
			return i+1;
	}
	return -1;
}
//替换指定数据
table tihuan(table t, int elme, int add)
{
	int i=select(t,elme);
	
		t.head[i-1] = add;
		return t;
	
}
//主函数
int main()
{
	xinxi();
	table t = initcreact();
	t = fuzhi(t);
	t = prt(t);
	int elme;
	printf("请输入插入的位置:");
	scanf("%d", &elme);
	int add;
	printf("请输入插入数据:");
	scanf("%d", &add);
	if (elme > t.size+1 || elme < 0)
	{
		printf("输入的位置错误\n");
		exit(0);
	}
	t = insert(t, elme,add);
	t = prt(t);
	printf("请输入删除的位置:");
	scanf("%d", &elme);
	if (elme > t.size || elme < 0)
	{
		printf("输入的位置错误\n");
		exit(0);
	}
	t = deleter(t, elme);
	t = prt(t);
	printf("查找 5 的位置\n");
	elme = select(t, 5);
	printf("5 的位置是 %d\n", elme);

	t = prt(t);
	printf("用 55 替换 5\n");
	tihuan(t, 5, 55);
	t = prt(t);

	system("pause");
	return 0;
}

 

 

  • 96
    点赞
  • 480
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值