点击查看代码
#include <stdio.h>
#include <stdlib.h>
typedef int dataType;
typedef struct
{
dataType *dataEntrance; // 顺序表数据的首地址
int numOfElement; // 元素个数
int lastIndex; // 当前顺序表最后一个元素的下标
} List, *pList;
// 顺序表初始化
pList InitSequentialList(void);
// 添加元素
void AddElement(dataType data, pList ptr);
// 按照索引删除元素
void DeleElement(int index, pList ptr);
// 显示顺序表数据
void ShowData(pList ptr);
int main(int argc, char const *argv[])
{
pList list = InitSequentialList();
for (size_t i = 0; i < list->numOfElement; i++)
{
AddElement(i, list);
}
DeleElement(8, list);
ShowData(list);
return 0;
}
pList InitSequentialList(void)
{
// 确定顺序表元素的个数
int sizeOfNum = 0;
printf("Please input the num of element:\n");
scanf("%d", &sizeOfNum);
// 申请一个结构体的空间,并初始化
pList ptr = calloc(1, sizeof(List));
ptr->dataEntrance = calloc(sizeOfNum, sizeof(dataType));
ptr->lastIndex = 0;
ptr->numOfElement = sizeOfNum;
return ptr;
}
/**
* @brief 添加元素
*
* @param data 待添加进顺序表的元素
* @param ptr 顺序表的地址
*/
void AddElement(dataType data, pList ptr)
{
// 判断顺序表是否已满
if (ptr->lastIndex == ptr->numOfElement || ptr == NULL)
{
printf("The sequential list overflow\n");
return;
}
ptr->dataEntrance[ptr->lastIndex] = data;
ptr->lastIndex++;
if (ptr->lastIndex == ptr->numOfElement)
{
ptr->lastIndex -= 1;
}
return;
}
void DeleElement(int index, pList ptr)
{
if (index > ptr->numOfElement - 1 || ptr == NULL)
{
printf("Your index is not exit\n");
return;
}
for (size_t i = index; i < ptr->lastIndex; i++)
{
ptr->dataEntrance[i] = ptr->dataEntrance[i + 1];
}
ptr->dataEntrance[ptr->lastIndex] = 0;
ptr->lastIndex -= 1;
return;
}
void ShowData(pList ptr)
{
if (ptr == NULL || ptr->lastIndex == 0)
{
printf("Your sequential list has no data\n");
return;
}
for (size_t i = 0; i <= ptr->lastIndex; i++)
{
printf("%d ", ptr->dataEntrance[i]);
}
return;
}