顺序表插入删除

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

一、头文件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;
}
相关推荐
潼心1412o8 小时前
数据结构(长期更新)第8讲:队列
数据结构
fashion 道格9 小时前
C 语言希尔排序:原理、实现与性能深度解析
数据结构·算法·排序算法
如意猴9 小时前
实现链式结构二叉树--递归中的暴力美学(第13讲)
数据结构
初夏睡觉9 小时前
P1048 [NOIP 2005 普及组] 采药
数据结构·c++·算法
Zero不爱吃饭10 小时前
环形链表(C)
数据结构·链表
xiaoye-duck10 小时前
数据结构之二叉树-链式结构(下)
数据结构·算法
Kt&Rs10 小时前
11.13 LeetCode 题目汇总与解题思路
数据结构·算法
yuuki23323311 小时前
【数据结构】常见时间复杂度以及空间复杂度
c语言·数据结构·后端·算法
前端小L12 小时前
图论专题(五):图遍历的“终极考验”——深度「克隆图」
数据结构·算法·深度优先·图论·宽度优先
代码不停12 小时前
Java分治算法题目练习(快速/归并排序)
java·数据结构·算法