pragma once
//不定长顺序表
#define OK 0
#define INDEX_ERROR 1
#define POINT_NULL 2
#define FOUND_ERROR 3
typedef int State;
typedef struct DSeqList
{
int *elem;//指向动态创建的内存
int length;//有效数据个数
int listsize;//总格子数
}DSeqList,*PDSeqList;//12
#define INIT_SIZE 10
//初始化顺序表ps
State InitSeqList(PDSeqList ps)
{
assert(ps != NULL);
if(ps == NULL)
{
return POINT_NULL;
}
ps->elem = (int *)malloc(INIT_SIZE*sizeof(int));
ps->length = 0;
ps->listsize = INIT_SIZE;
return OK;
}
static bool IsFull(PDSeqList ps)
{
return ps->length == ps->listsize;
}
//将总格子数扩大2倍(1.5倍)
static void Inc(PDSeqList ps)
{
ps->elem = (int *)realloc(ps->elem,ps->listsize*2*sizeof(int));
ps->listsize *= 2;
}
//在顺序表ps中的第pos位置插入val
State Insert(PDSeqList ps,int pos,int val)
{
if(pos<0 || pos>ps->length)
{
return INDEX_ERROR;
}
if(IsFull(ps))
{
Inc(ps);
}
for(int i=ps->length-1;i>=pos;i--)//移动数据
{
ps->elem[i+1] = ps->elem[i];
}
ps->elem[pos] = val;
ps->length++;
return OK;
}
//在顺序表ps中查找key,如果找到返回下标,没有找到返回-1
int Search(PDSeqList ps,int key)
{
for(int i=0;i<ps->length;i++)
{
if(ps->elem[i] == key)
{
return i;
}
}
return -1;
}
//在ps中删除关键字key,成功返回true
State DeleteVal(PDSeqList ps,int key)
{
int index = Search(ps,key);
if(index < 0)
{
return FOUND_ERROR;
}
return DeletePos(ps,index);
}
//删除第pos位置的值
State DeletePos(PDSeqList ps,int pos)
{
if(pos<0 || pos>=ps->length)
{
return INDEX_ERROR;
}
for(int i=pos;i+1<ps->length;i++)
{
ps->elem[i] = ps->elem[i+1];
}
ps->length--;
return OK;
}
//获取pos位置的值
State GetElem(PDSeqList ps,int pos,int *rtval)
{
if(pos<0 || pos>=ps->length)
{
return INDEX_ERROR;
}
if(rtval != NULL)
{
*rtval = ps->elem[pos];
}
return OK;
}
//将pos位置的值设为val
State SetElem(PDSeqList ps,int pos,int val)
{
if(pos<0 || pos>=ps->length)
{
return INDEX_ERROR;
}
ps->elem[pos] = val;
return OK;
}
在这里扩容不一定是扩容1.5倍也可能是2倍,根据编译器的情况判断