文章目录
头文件
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#define INIT_CAPACITY 4
typedef int SLDataType;
typedef struct SeqList {
SLDataType* a;
int size;
int capacity;
}SL;
void SLPrint(SL* ps);
void SLInit(SL* ps);
void SLDestory(SL* ps);
void SLCheckCapacity(SL* ps);
void SLPushBack(SL* ps, SLDataType x);
void SLPushFront(SL* ps, SLDataType x);
void SLPopBack(SL* ps);
void SLPopFront(SL* ps);
void SLInsert(SL* ps, int pos, SLDataType x);
void SLInsert(SL* ps, int pos, SLDataType x);
void SLErase(SL* ps, int pos);
实现文件
#define _CRT_SECURE_NO_WARNINGS 1
#include"SeqList.h"
void SLPrint(SL* ps)
{
assert(ps);
for (int i = 0; i < ps->size; i++)
{
printf("%d ", ps->a[i]);
}
printf("\n");
}
void SLInit(SL* ps)
{
ps->size = 0;
ps->capacity = INIT_CAPACITY;
SLDataType* arr = (SLDataType*)malloc(sizeof(SLDataType) * INIT_CAPACITY);
if (arr == NULL) {
perror("malloc fail!\n");
exit(1);
}
else {
ps->a = arr;
arr = NULL;
}
}
void SLDestory(SL* ps)
{
assert(ps);
if(ps->a)
free(ps->a);
ps->a = NULL;
ps->size = 0;
ps->capacity = 0;
}
void SLCheckCapacity(SL* ps)
{
assert(ps);
if (ps->size == ps->capacity)
{
ps->capacity *= 2;
SLDataType* arr = (SLDataType*)realloc(ps->a, sizeof(SLDataType) * (ps->capacity));
if (arr == NULL)
{
perror("realloc fail!\n");
exit(1);
}
ps->a = arr;
}
}
void SLPushBack(SL* ps, SLDataType x)
{
assert(ps);
SLCheckCapacity(ps);
ps->a[ps->size] = x;
ps->size++;
}
void SLPushFront(SL* ps, SLDataType x)
{
assert(ps);
SLCheckCapacity(ps);
for (int i = ps->size - 1; i >= 0; i--)
{
ps->a[i + 1] = ps->a[i];
}
ps->a[0] = x;
ps->size++;
}
void SLPopBack(SL* ps)
{
assert(ps);
assert(ps->size > 0);
ps->size--;
}
void SLPopFront(SL* ps)
{
assert(ps);
assert(ps->size > 0);
for (int i = 0; i < ps->size - 1; i++) {
ps->a[i] = ps->a[i + 1];
}
ps->size--;
}
int SLFind(SL* ps, SLDataType x)
{
assert(ps);
for (int i = 0; i < ps->size; i++)
{
if (ps->a[i] == x)
return i;
}
return -1;
}
void SLInsert(SL* ps, int pos, SLDataType x)
{
assert(ps);
assert(pos <= ps->size && ps >= 0);
SLCheckCapacity(ps);
for (int i = ps->size - 1; i >= pos; i--)
{
ps->a[i + 1] = ps->a[i];
}
ps->a[pos] = x;
ps->size++;
}
void SLErase(SL* ps, int pos)
{
assert(ps);
assert(pos <= ps->size && ps >= 0);
for (int i = pos; i < ps->size - 1; i++)
{
ps->a[i] = ps->a[i + 1];
}
ps->size--;
}
测试文件
#define _CRT_SECURE_NO_WARNINGS 1
#include"SeqList.h"
void Test1()
{
SL* ps = (SL*)malloc(sizeof(SL*));
SLInit(ps);
SLPushBack(ps, 1);
SLPushBack(ps, 2);
SLPushBack(ps, 3);
SLPushBack(ps, 4);
SLInsert(ps, 3, 0);
SLErase(ps, 3);
SLPrint(ps);
SLDestory(ps);
}
int main()
{
Test1();
return 0;
}