b.不定长顺序表的实现
同样,先给出结构体的定义部分:
typedef int ELEMTYPE;
#define INIT_SIZE 10 //默认初始长度
typedef struct DSqlist
{
ELEMTYPE*data;
int length; //有效空间长度
int listsize; //当前最大长度
}DSqlist, * PDSqlist;
简单函数的定义:
//初始化
void Init_sqlist(PDSqlist plist)
{
assert(plist != NULL);
plist->data = (ELEMTYPE*)malloc(sizeof(ELEMTYPE) * INIT_SIZE);
if (plist->data == NULL)
{
exit(1);
}
plist->length = 0;
plist->listsize = INIT_SIZE;
}
//扩容
void Inc(PDSqlist plist)
{
assert(plist != NULL);
//1.5倍扩容
plist->data = (ELEMTYPE*)realloc(plist->data, sizeof(ELEMTYPE) * plist->listsize * 1.5);
if (plist->data == NULL)
{
return;
}
plist->listsize *= 1.5;
}
//打印
void Print_sqlist(PDSqlist plist)
{
assert(plist != NULL);
for (int i = 0; i < plist->length; i++)
{
printf("%d ", plist->data[i]);
}
printf("\n");
}
//按位置插入
bool Insert_pos(PDSqlist plist, int pos, int val)
{
assert(plist != NULL);
assert(pos >= 0 && pos <= plist->length);
if (IsFull(plist)) //判满
{
Inc(plist);
}
for (int i = plist->length - 1; i >= pos; i--)
{
plist->data[i + 1] = plist->data[i];
}
plist->data[pos] = val;
plist->length++;
return true;
}
//按值删除
bool Del_val(PDSqlist plist, int val)
{
assert(plist != NULL);
//是否空
if (IsEmpty(plist))
{
return false;
}
int pos = Search_val(plist, val);
if (pos == -1) return false;
else
{
Del_pos(plist, pos);
}
return true;
}
//按位置删除
bool Del_pos(PDSqlist plist, int pos)
{
assert(plist != NULL);
assert(pos > 0 && pos <= plist->length);
for (int i = pos; i < plist->length - 1; i++)
{
plist->data[i] = plist->data[i + 1];
}
plist->length--;
return true;
}
//查找val的结点
int Search_val(PDSqlist plist, int val)
{
assert(plist != NULL);
for (int i = 0; i < plist->length; i++)
{
if (plist->data[i] == val)
return i;
}
return -1;
}
//判空
bool IsEmpty(PDSqlist plist)
{
assert(plist != NULL);
return plist->length == 0;
}
//判满
bool IsFull(PDSqlist plist)
{
assert(plist != NULL);
return plist->length == plist->listsize;
}
//清空
bool Clear(PDSqlist plist)
{
assert(plist != NULL);
plist->length = 0;
return true;
}
//销毁
bool Destory(PDSqlist plist)
{
assert(plist != NULL);
free(plist->data);
plist->data = NULL;
plist->length = plist->listsize = 0;
return true;
}