顺序表插入删除

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

一、头文件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;
}
相关推荐
why1515 小时前
面经整理——算法
java·数据结构·算法
曾几何时`9 小时前
归并排序(一)
数据结构·算法·leetcode
业精于勤的牙10 小时前
小张刷题计划(二)
数据结构·算法
亮子AI12 小时前
【Tiptap】如何使用 ordered list?
数据结构·list·tiptap
南莺莺12 小时前
二叉排序树的创建和基本操作---C++实现
数据结构·c++·算法··二叉排序树
仰泳的熊猫12 小时前
1061 Dating
数据结构·c++·算法·pat考试
Fcy64812 小时前
二叉搜索树(C++实现)
开发语言·数据结构·c++·二叉搜索树
CoderYanger12 小时前
A.每日一题——1523. 在区间范围内统计奇数数目
java·数据结构·算法·leetcode·职场和发展
surtr112 小时前
Round 1019(div2) CD
数据结构·c++·算法·贪心算法·stl
冰西瓜60012 小时前
分治(二)算法设计与分析 国科大
数据结构·算法