C语言-顺序表

C语言-顺序表

顺序表:

是在计算机内存中以数组的形式保存的线性表,是指用一组地址连续的存储单元依次存储数据元素的线性结构。线性表采用顺序存储的方式存储就称之为顺序表。顺序表是将
表中的结点依次存放在计算机内存中一组地址连续的存储单元中

typedef struct {
	int id;
	char name[20];
}ElementType;//定义ElementType变量

typedef struct {
	ElementType datas[MAX_SIZE];//能插入元素的最大容量大小
	int length;//当前顺序表的长度
}SeqList;//定义顺序表的结构体

void InitSequence(SeqList* seqList, ElementType* elemArray, int length);
//上面是初始化顺序表
void InsertSequence(SeqList* seqList, int index, ElementType elemArray);
//上面是向顺序表插入元素,其中index是想向数组中插入的位置
void PrintSequence(SeqList* seqList);
//上面是打印顺序表

以下是具体实现代码:

void InitSequence(SeqList* seqList, ElementType* elemArray, int length)
{
	if (length > MAX_SIZE)
	{
		printf("当前长度超过数组的最大容量");
		return;
	}
	seqList->length = 0;
	for (int i = 0; i < length; i++)
	{
		InsertSequence(seqList, i, elemArray[i]);
	}
}

void InsertSequence(SeqList* seqList, int index, ElementType elemArray)
{
	if (seqList->length + 1 > MAX_SIZE)
	{
		printf("插入失败,超过数组的最大长度");
		return;
	}
	if (index < 0 || index >MAX_SIZE)
	{
		printf("插入的下标不在数组的范围内");
		return;
	}
	if (index > seqList->length)
	{
		printf("插入下标超过了数组的长度");
		return;
	}
	for (int i = seqList->length - 1; i >= index; i--)
	{
		seqList->datas[i + 1] = seqList->datas[i];
	}
	seqList->datas[index] = elemArray;
	seqList->length++;
}

void PrintSequence(SeqList* seqList)
{
	for (int i = 0; i < seqList->length; i++)
	{
		printf("%d\t%s\n", seqList->datas[i].id, seqList->datas[i].name);
	}
}

以下是主函数中调用:

void TestSequence();

ElementType elemArray[]=
{
	{1,"小米"},
	{2,"小说"},
    {3,"萨达"}
};

int main()
{
	TestSequence();
	return 0;
}

void TestSequence()
{
	SeqList seqList;
	InitSequence(&seqList, elemArray, 3);
	PrintSequence(&seqList);
}

以下是运行结果:
在这里插入图片描述

发布了5 篇原创文章 · 获赞 0 · 访问量 58

猜你喜欢

转载自blog.csdn.net/qq_44704200/article/details/105176848