84.【C语言】数据结构之顺序表的头部插入和删除

目录

3.操作顺序表

1.分析头部插入函数

SeqList.c写入

容量检查函数

注意

main.c改为

SeqList.h添加SLPushFront的声明

运行结果

2.分析头部删除函数

SLPopFront代码

main.c改为

SeqList.h添加SLPopFront的声明

图分析

运行结果


承接83.【C语言】数据结构之顺序表的尾部插入和删除文章

3.操作顺序表

1.分析头部插入函数

SeqList.c写入

cpp 复制代码
void SLPushFront(SL* ps,SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	int end = ps->size-1;//定义尾部,一开始a[end-1]指向最后一个元素
	while (end >= 0)//注意循环条件
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[0] = x;
	ps->size++;
}

容量检查函数

cpp 复制代码
void SLCheckCapacity(SL* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		SLDataType* tmp = (SLDataType*)realloc(ps->a, sizeof(SLDataType) * ps->capacity * 2);
		if (tmp == NULL)
		{
			perror("realloc");
			return;//错误返回
		}
		ps->capacity *= 2;
		ps->a = tmp;
	}
}

注意

头插时,元素会逐个向后移动,因此要先进行容量检查,再移动元素,最后不要忘记为有效元素个数size+1;

main.c改为

cpp 复制代码
#include "SeqList.h"
//定义测试顺序表的函数
void TestSeqList1()
{
	SL s;
	SLInit(&s);
	SLPushBack(&s, 1);
	SLPushBack(&s, 2);
	SLPushBack(&s, 3);
	SLPushBack(&s, 4);
	SLPrint(&s);
	SLPushFront(&s, 1);
	SLPrint(&s);
	SLDestory(&s);
}

int main()
{
	TestSeqList1();
	return 0;
}

SeqList.h添加SLPushFront的声明

运行结果

头插N个元素的时间复杂度为,运行效率不高,尽量避免头插,使用尾插(尾插N个元素的时间复杂度为)

2.分析头部删除函数

SLPopFront代码

cpp 复制代码
void SLPopFront(SL * ps)
{
	assert(ps);
	assert(ps->size);
	int begin = 1;
	while (begin < ps->size)
	{
		ps->a[begin - 1] = ps->a[begin];
		begin++;
	}
	ps->size--;
}

注:ps->size可能为负数,因此要断言ps->size的正负

main.c改为

cpp 复制代码
void TestSeqList1()
{
	SL s;
	SLInit(&s);
	SLPushBack(&s, 1);
	SLPushBack(&s, 2);
	SLPushBack(&s, 3);
	SLPushBack(&s, 4);
	SLPushBack(&s, 5);
	SLPrint(&s);
	SLPopFront(&s);
	SLPrint(&s);
	SLDestory(&s);
}

SeqList.h添加SLPopFront的声明

图分析

运行结果

相关推荐
祈安_16 小时前
C语言内存函数
c语言·后端
郑州光合科技余经理2 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1232 天前
matlab画图工具
开发语言·matlab
dustcell.2 天前
haproxy七层代理
java·开发语言·前端
norlan_jame2 天前
C-PHY与D-PHY差异
c语言·开发语言
琢磨先生David2 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054962 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
czy87874752 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
遥遥江上月2 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js