顺序表的初始化、销毁、打印、头插、尾插、头删、尾删
一、头文件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;
}