顺序表插入删除

顺序表的初始化、销毁、打印、头插、尾插、头删、尾删

一、头文件SeqList.h

复制代码
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
//静态顺序表
//typedef N 100
//struct SeqList
//{
//	int arr[N];
//	int size;//有效数据个数
//};

//动态顺序表
typedef int SLDataType;
typedef struct SeqList
{
	SLDataType* arr;
	int size;//有效数据个数
	int capacity;//空间大小
}SL;
//初始化
void SLInit(SL* ps);
//销毁
void SLDestroy(SL* ps);
//扩容
void SLCheckCapacity(SL* ps);
//打印
void SLPrint(SL ps);
//头插
void SLPushFront(SL* ps, SLDataType x);
//尾插
void SLPushBack(SL* ps, SLDataType x);
//头删
void SLPopFront(SL* ps);
//尾删
void SLPopBack(SL* ps);

二、SeqList.c文件

复制代码
#include"SeqList.h"
//初始化
void SLInit(SL* ps)
{
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}
//销毁
void SLDestroy(SL* ps)
{
	if (ps->arr != NULL)
	{
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}
//扩容
void SLCheckCapacity(SL* ps)
{
	//插入数据之前看看空间够不够
	if (ps->size == ps->capacity)
	{
		//申请空间
		int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		SLDataType* tmp = (SLDataType*)realloc(ps->arr, newCapacity * sizeof(SLDataType));
		if (tmp == NULL)
		{
			perror("realloc fail!");
			exit(1);//直接退出程序,不再执行
		}
		//空间申请成功
		ps->arr = tmp;
		ps->capacity = newCapacity;
	}
}
//打印
void SLPrint(SL ps)
{
	for (int i = 0; i <ps.size; i++)
	{
		printf("%d ", ps.arr[i]);
	}
	printf("\n");
}
//头插
void SLPushFront(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	for (int i = ps->size; i > 0; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
	ps->size++;
}
//尾插
void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	ps->arr[ps->size] = x;
	ps->size++;
}
//头删
void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size != NULL);
	for (int i = 0; i < ps->size-1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];//arr[size-2]=arr[size-1]
	}
	ps->size--;
}
//尾删
void SLPopBack(SL* ps)
{
	assert(ps);
	assert(ps->arr != NULL);
	ps->arr[ps->size - 1] = -1;
	ps->size--;
}

三、测试文件

复制代码
#include"SeqList.h"
void SLTest()
{
	SL sl;
	SLInit(&sl);
	SLPushFront(&sl, 1);
	SLPushFront(&sl, 2);
	SLPushFront(&sl, 3);
	SLPushFront(&sl, 4);
	SLPrint(sl);

	////测试尾插
	//SLPushBack(&sl, 6);
	//SLPushBack(&sl, 7);
	//SLPushBack(&sl, 8);
	//SLPushBack(&sl, 9);
	//SLPrint(sl);

	////测试头删
	//SLPopFront(&sl);
	//SLPopFront(&sl);
	//SLPrint(sl);

	//测试尾删
	SLPopBack(&sl);
	SLPopBack(&sl);
	SLPrint(sl);

	SLDestroy(&sl);
}
int main()
{
	SLTest();
	return 0;
}
相关推荐
一起养小猫1 小时前
LeetCode100天Day9-无重复字符的最长子串与赎金信
java·开发语言·数据结构·leetcode
white-persist2 小时前
【内网运维】Netstat与Wireshark:内网运维溯源实战解析
运维·网络·数据结构·测试工具·算法·网络安全·wireshark
啊董dong2 小时前
noi-2025年12月23号作业
数据结构·c++·算法·noi
夏乌_Wx2 小时前
练题100天——DAY35:棒球比赛+数组的度
数据结构
youngee112 小时前
hot100-63买卖股票的最佳时机
数据结构·算法·leetcode
爱吃生蚝的于勒2 小时前
【Linux】零基础深入学习动静态库+深入学习地址
linux·运维·服务器·c语言·数据结构·c++·学习
万象.3 小时前
redis通用命令与数据结构
数据结构·数据库·redis
小宇的天下3 小时前
Calibre : 一个简单的DRC rule file
数据结构
C雨后彩虹3 小时前
ReentrantLock入门:核心特性与基本使用
java·数据结构·reentrantlock·lock
你撅嘴真丑3 小时前
短信计费 和 甲流病人初筛
数据结构·c++·算法