顺序表插入删除

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

一、头文件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;
}
相关推荐
琢磨先生David5 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245035 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA5 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc5 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg15 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA5 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX5 天前
020-C++之unordered容器
数据结构·c++
岛雨QA5 天前
多路查找树「Java数据结构与算法学习笔记11」
数据结构·算法
AKA__Zas5 天前
初识基本排序
java·数据结构·学习方法·排序