typedef struct SeqList//定长顺序表
{
int elem[SIZE];
int length;//有效数据个数
}SeqList,*PSeqList;//44
//初始化顺序表ps
void InitSeqList(PSeqList ps)//PSeqList == SeqList *;
{
assert(ps != NULL);
if(ps == NULL)
{
return ;
}
ps->length = 0;//有效数据个数为0
}
//判断顺序表是否为满
static bool IsFull(PSeqList ps)
{
return ps->length == SIZE;
}
//在顺序表ps中的第pos位置插入val
bool Insert(PSeqList ps,int pos,int val)
{
if(pos<0 || pos>ps->length || IsFull(ps))
{
return false;
}
for(int i=ps->length-1;i>=pos;i--)//1、移动后面的数据
{
ps->elem[i+1] = ps->elem[i];
}
ps->elem[pos] = val;//2、插入
ps->length++;//3、长度+1
return true;
}
//在顺序表ps中查找key,如果找到返回下标,没有找到返回-1
int Search(PSeqList ps,int key)
{
for(int i=0;i<ps->length;i++)
{
if(ps->elem[i] == key)
{
return i;
}
}
return -1;
}
//在ps中删除关键字key,成功返回true
bool DeleteVal(PSeqList ps,int key)
{
int index = Search(ps,key);
return DeletePos(ps,index);
}
//删除第pos位置的值
bool DeletePos(PSeqList ps,int pos)
{
if(pos<0 || pos>=ps->length)
{
return false;
}
for(int i=pos;i<ps->length-1;i++)
{
ps->elem[i] = ps->elem[i+1];
}
ps->length--;
return true;
}
//获取pos位置的值
bool GetElem(PSeqList ps,int pos,int *rtval)
{
if(pos<0 || pos>=ps->length)
{
return false;
}
if(rtval != NULL)
{
*rtval = ps->elem[pos];
}
return true;
}
//将pos位置的值设为val
bool SetElem(PSeqList ps,int pos,int val)
{
if(pos<0 || pos>=ps->length)
{
return false;
}
ps->elem[pos] = val;
return true;
}
//获取关键字key的前驱值
bool GetPrio(PSeqList ps,int key,int *rtval)
{
int index = Search(ps,key);
if(index <= 0)
{
return false;
}
*rtval = ps->elem[index-1];
return true;
}