1.顺序表的销毁和初始化:
初始化:
c
void SLInit(SeqList* ps)
{
ps->a = NULL;
ps->capacity = 0;
ps->size = 0;
}
销毁:
c
void SLDestroy(SeqList* ps)
{
if (ps->a)
free(ps->a);
ps->a = NULL;
ps->size = ps->capacity = 0;
}
2.顺序表的扩容及打印:
扩容:
c
void CheckRoom(SeqList* ps)
{
if (ps->size == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
SLDataType* tem = (SLDataType*)realloc(ps->a, sizeof(SLDataType) * newcapacity);
ps->a = tem;
ps->capacity = newcapacity;
}
}
打印:
c
void PrintList(SeqList* ps)
{
int i = 0;
for (i = 0;i < ps->size;i++)
{
printf("%d ", ps->a[i]);
}
}
3.在顺序表的头部或尾部插入数据:
头插:
c
void PushFront(SeqList* ps,SLDataType x)
{
CheckRoom(ps);
int i = ps->size;
for (i = ps->size - 1;i >= 0;i--)
{
ps->a[i + 1] = ps->a[i];
}
ps->a[0] = x;
ps->size++;
}
尾插:
c
void PushBack(SeqList* ps, SLDataType x)
{
CheckRoom(ps);
ps->a[ps->size] = x;
ps->size++;
}
4.删除顺序表头部或尾部的数据:
头删:
c
void PopFront(SeqList* ps)
{
assert(ps);
assert(ps->size);
for (int i = 1;i < ps->size;i++)
{
ps->a[i - 1] = ps->a[i];
}
ps->size--;
}
尾删:
c
void PopBack(SeqList* ps)
{
assert(ps);
assert(ps->size);
ps->size--;
}
5.删除指定元素:
c
void Insert(SeqList* ps, SLDataType x)
{
assert(ps);
assert(ps->size);
int i=Find(ps, x)-1;
if (i < 0)
{
printf("未找到数据\n");
}
else
{
for (i;i < ps->size-1;i++)
{
ps->a[i] = ps->a[i + 1];
}
ps->size--;
}
}