定义顺序表结构
#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;
}