目录

数据结构-顺序表

数据结构–顺序表

顺序表是线性表的一种存储结构,用一组地址连续的存储单元依次存储线性表的数据元素。它把逻辑上相邻的数据元素存储在物理位置上也相邻的存储单元中,元素之间的逻辑关系由存储单元的邻接关系来体现。

  1. 容量检查和扩容 :SeqListCheckCapacity 会检查顺序表是否已满,若满则进行扩容操作,扩容策略是初始容量为 4,后续每次扩容为原来的 2 倍。
  2. 插入和删除操作 :支持头插(SeqListPushFront)、尾插(SeqListPushBack)、头删(SeqListPopFront)、尾删(SeqListPopBack),以及在指定位置插入(SeqListInsert)和删除元素(SeqListErase)。
  3. 查找和修改操作 :SeqListFind 用于查找指定元素的位置,SeqListModity 用于修改指定位置的元素值。
  4. 打印操作 :SeqListPrint 用于打印顺序表中的所有元素。
void SeqListInit(SL* ps)
{
	ps->a = NULL;
	ps->size = 0;
	ps->capacity = 0;
}
void SeqListDestory(SL* ps)
{
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->size = 0;
}
void SeqListCheckCapacity(SL* ps)
{
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SQDataType* tmp = (SQDataType*)realloc(ps->a, newcapacity * sizeof(SQDataType));
		if (tmp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		else
		{
			ps->a = tmp;
			ps->capacity = newcapacity;
		}
	}
}
void SeqListPrint(SL* ps)
{
	for (int i = 0; i < ps->size; ++i)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}
void SeqListPushBack(SL* ps, SQDataType x)
{
	SeqListCheckCapacity(ps);
	ps->a[ps->size] = x;
	ps->size++;
}
void SeqListPushFront(SL* ps, SQDataType x)
{
	SeqListCheckCapacity(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 start = 1;
	while (start < ps->size)
	{
		ps->a[start - 1] = ps->a[start];
		++start;
	}
	ps->size--;
}
void SeqListPopBack(SL* ps)
{
	assert(ps->size > 0);
	ps->a[ps->size - 1] = 0;
	ps->size--;
}
void SeqListInsert(SL* ps, int pos, SQDataType x)
{
	assert(pos <= ps->size);
	SeqListCheckCapacity(ps);
	int end = ps->size - 1;
	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		--end;
	}
	ps->a[pos] = x;
	ps->size++;
}
void SeqListErase(SL* ps, int pos)
{
	assert(pos < ps->size);
	int start = pos + 1;
	while (start < ps->size)
	{
		ps->a[start-1] = ps->a[start];
		++start;
	}
	ps->size--;
}
int SeqListFind(SL* ps, SQDataType x)
{
	for (int i = 0; i < ps->size; ++i)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}
void SeqListModity(SL* ps, int pos, SQDataType x)
{
	assert(pos < ps->size);
	ps->a[pos] = x;
}