SeqList.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
typedef int SLDatatype;
typedef struct SeqList
{
SLDatatype *a;
int size;
int capacity;
}SeqList;
void SeqListInit(SeqList *psl);
void SeqListDestory(SeqList *psl);
void SeqListPrint(SeqList *psl);
void CheckCapacity(SeqList *psl);
void SeqListPushBack(SeqList *psl, SLDatatype x);
void SeqListPopBack(SeqList *psl);
void SeqListPushFront(SeqList *psl, SLDatatype x);
void SeqListPopFront(SeqList *psl);
SeqList.c
#include "SeqList.h"
void SeqListInit(SeqList *psl)
{
psl->a = (SLDatatype*)malloc(sizeof(SLDatatype)* 4);
if (psl->a == NULL)
{
printf("malloc fail\n");
exit(-1);
}
memset(psl->a, 0, sizeof(SLDatatype)* 4);
psl->capacity = 4;
psl->size = 0;
}
void SeqListDestory(SeqList *psl)
{
free(psl->a);
psl->a = NULL;
psl->capacity = psl->size = 0;
}
void SeqListPrint(SeqList *psl)
{
for (int i = 0; i < psl->size; i++)
{
printf("%d ", psl->a[i]);
}
printf("\n");
}
void CheckCapacity(SeqList *psl)
{
if (psl->capacity == psl->size)
{
SLDatatype *tmp = realloc(psl->a, sizeof(SLDatatype)*psl->capacity * 2);
if (tmp == NULL)
{
printf("realloc fail\n");
exit(-1);
}
psl->a = tmp;
psl->capacity = psl->capacity * 2;
}
}
void SeqListPushBack(SeqList *psl, SLDatatype x)
{
assert(psl);
CheckCapacity(psl);
psl->a[psl->size] = x;
psl->size++;
}
void SeqListPopBack(SeqList *psl)
{
assert(psl);
assert(psl->size > 0);
psl->size--;
}
void SeqListPushFront(SeqList *psl, SLDatatype x)
{
assert(psl);
CheckCapacity(psl);
int end = psl->size - 1;
while (end >= 0)
{
psl->a[end + 1] = psl->a[end];
end--;
}
psl-> a[0] = x;
psl->size++;
}
void SeqListPopFront(SeqList *psl)
{
assert(psl);
assert(psl->size > 0);
int begin = 1;
while (begin < psl->size)
{
psl->a[begin - 1] = psl->a[begin];
begin++;
}
psl->size--;
}
Test.c
#include"SeqList.h"
int main()
{
SeqList s;
SeqListInit(&s);
SeqListPushBack(&s, 1);
SeqListPushBack(&s, 2);
SeqListPushBack(&s, 3);
SeqListPushBack(&s, 4);
SeqListPushBack(&s, 5);
printf("PushBack:");
SeqListPrint(&s);
SeqListPushFront(&s, 11);
SeqListPushFront(&s, 12);
SeqListPushFront(&s, 13);
printf("PushFront:");
SeqListPrint(&s);
SeqListPopFront(&s);
printf("PopFront:");
SeqListPrint(&s);
SeqListPopBack(&s);
printf("PopBack:");
SeqListPrint(&s);
SeqListDestory(&s);
return 0;
}
测试结果