【C语言】【数据结构】【顺序表】

1.顺序表的销毁和初始化:

初始化:

void SLInit(SeqList* ps)
{
	ps->a = NULL;
	ps->capacity = 0;
	ps->size = 0;
}

销毁:

void SLDestroy(SeqList* ps)
{
	if (ps->a)
		free(ps->a);
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}

2.顺序表的扩容及打印:

扩容:

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;
	}
}

打印:

void PrintList(SeqList* ps)
{
	int i = 0;
	for (i = 0;i < ps->size;i++)
	{
		printf("%d ", ps->a[i]);
	}
}

3.在顺序表的头部或尾部插入数据:

头插:

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++;
}

尾插:

void PushBack(SeqList* ps, SLDataType x)
{
	CheckRoom(ps);
	ps->a[ps->size] = x;
	ps->size++;
}

4.删除顺序表头部或尾部的数据:

头删:

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--;
}

尾删:

void PopBack(SeqList* ps)
{
	assert(ps);
	assert(ps->size);
	ps->size--;

}

5.删除指定元素:

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--;
	}
}

你可能感兴趣的:(c语言,数据结构,开发语言,学习,笔记,学习方法)