#include <stdio.h>
#include <stdlib.h>
#define N 10
typedef struct seqlist //封装顺序表结构体类型
{
int data[N]; //用来存数据的数组
int last; //代表数组中最后一个有效元素的下标
} seqlist_t, *seqlist_p;
// 创建一个空的顺序表
seqlist_p CreateEpSeqlist() //create创造 empty 空的 seqlist顺序表
{
//动态申请一块顺序表结构体大小空间
seqlist_p p = (seqlist_p)malloc(sizeof(seqlist_t));
if (NULL == p)
{
perror("malloc lost"); //perror打印上一个函数报的错误信息
return NULL; //错误情况让函数返回空指针
}
//对结构体初始化
p->last = -1;
return p;
}
//判断顺序表是否为满,满返回1,未满返回0
int IsFullSeqlist(seqlist_p p) //full满
{
return p->last + 1 == N;
}
//向顺序表的指定位置插入数据
int InsertIntoSeqlist(seqlist_p p, int post, int data)
{
//容错判断:判满,对post做判断
if (IsFullSeqlist(p) || post < 0 || post > p->last + 1)
{
printf("InsertIntoSeqlist err\n");
return -1; //错误返回
}
//让最后一个元素到插入位置的元素向后移动一个单位
for (int i = p->last; i >= post; i--)
p->data[i + 1] = p->data[i];
//插入数据
p->data[post] = data;
//让last加一
p->last++;
return 0;
}
//遍历顺序表sequence顺序list表
void ShowSeqlist(seqlist_p p)
{
for (int i = 0; i <= p->last; i++)
printf("%d ", p->data[i]);
printf("\n");
}
//判断顺序表是否为空,为空返回1,不为空返回0
int IsEpSeqlist(seqlist_p p)
{
return p->last == -1;
}
//删除顺序表中指定位置的数据,post为删除位置
int DeleteIntoSeqlist(seqlist_p p, int post)
{
//容错判断:判空,对post判断
if (IsEpSeqlist(p) || post < 0 || post > p->last)
{
printf("DeleteIntoSeqlist err\n");
return -1;
}
//从删除位置元素的后一个元素到最后一个元素向前移动一个单位
for (int i = post + 1; i <= p->last; i++)
p->data[i - 1] = p->data[i];
//让last减一,因为删除了一个元素有效元素少了一个
p->last--;
return 0;
}
// 修改指定位置上数据
int ChangePostSeqList(seqlist_p p, int post, int data)
{
//容错判断:判空,对post判断
if (IsEpSeqlist(p) || post < 0 || post > p->last)
{
printf("ChangePostSeqList err\n");
return -1;
}
//修改指定位置数据
p->data[post] = data;
return 0;
}
// 查找指定数据出现的位置,返回下标,未找到返回-1
int SearchDataSeqList(seqlist_p p, int data)
{
for (int i = 0; i <= p->last; i++)
{
if (p->data[i] == data)
return i;
}
return -1;
}
// 清空顺序表(清空:访问不到,但是内存中还有。销毁:内存清空)
void ClearSeqList(seqlist_p p)
{
p->last = -1;
}
int main(int argc, char const *argv[])
{
seqlist_p p = CreateEpSeqlist();
InsertIntoSeqlist(p, 0, 10);
InsertIntoSeqlist(p, 1, 20);
InsertIntoSeqlist(p, 2, 30);
ShowSeqlist(p);
DeleteIntoSeqlist(p, 1);
ShowSeqlist(p);
ChangePostSeqList(p, 0, 99);
ShowSeqlist(p);
printf("search 99:%d\n", SearchDataSeqList(p, 99));
return 0;
}
04-26
1473
04-16
867
05-10
1643