知识点:顺序表(后续)
检查是否有存放空间:
void SeListCheckCapacity(SL*ps)
{
if(ps->size==ps->capacity)
{
int newcapacity=ps->capacity==0?4:ps->capacity*2;
SLDataType*tmp=(SLDataType*)realloc(ps->a,newcapacity*sizeof(SLDataType));
if(tmp==NULL)
{
printf("realloc fail\n");
exit(-1);
}
ps->a=tmp;
ps->capacity=newcapacity;
}
}
头插:
void SeListPushFront(SL*ps,SLDataType x)
{
SeListCheckCapacity(ps);
int end=ps->size-1;
while(end>=0)
{
ps->a[end+1]=ps->a[end];
--end;
}
ps->a[0]=x;
ps->size++;
}
头删:
void SeqListPopFront(SL*ps)
{
assert(ps->size>0);
int begin=1;
while(begin<ps->size)
{
ps->a[begin-1]=ps->a[begin];
++begin;
}
ps->size--;
}
查找一个数在顺序表中的位置:
int SeqListFind(SL*ps,SLDataType x)
{
for(int i=0;i<ps->size;i++)
{
if(ps->a[i]==x)
{
return i;
}
}
return -1;
}
在指定的pos下标位置插入:
void SeqListInsert(SL *ps,int pos,SLDataType x)
{
// if(pos>ps->size||pos<0)
// {
// printf("pos invalid\n");
// return;
// }
assert(pos>=0&&pos<=ps->size);
SeqListCheckCapacity(ps);
int end=ps->size-1;
while(end>=pos)
{
pd->a[end+1]=ps->a[end];
--end;
}
ps->a[pos]=x;
ps->size++;
}
在指定的pos下标位置删除:
void SeqListErase(SL*ps,int pos)
{
asser(pos>=0&&pos<ps->size);
int begin=pos+1;
while(begin<ps->size)
{
ps->a[begin-1]=ps->a[begin];
++begin;
}
ps->size--;
}
可用SeqListInert和SeqListErase函数来实现头插,尾插,头删,尾删,更加方便简洁。
SeqListFind可以和SeqListInsert和SeqListErase配合使用,更加简单便捷