SeqList.h文件
#pragma once #include<stdio.h> #include<stdlib.h> #define INIT_CAPACITY 4 typedef int SLDataType; #define N 10 typedef struct SeqList { SLDataType* a; int size; //有效数据个数 int capacity;//空间的容量 }SL; void SLInit(SL* ps); void SLDestory(SL* s); void SLExpend(SL* s); void Push_Back(SL* ps, SLDataType x); void Pop_Back(SL* ps); void SLPrint(SL* ps); void Push_Front(SL* ps, SLDataType x); void Pop_Front(SL* ps);
SeqList.c文件
#include"SeqList.h" void SeqInit(SL* ps) { ps->a= (SLDataType*)malloc(sizeof(SLDataType) * INIT_CAPACITY); if (ps->a == NULL) { perror("malloc fail"); } ps->size = 0; ps->capacity= INIT_CAPACITY; } void SLDestroy(SL* ps) { free(ps->a); ps->a = NULL; ps->capacity = 0; ps->size = 0; } void SLExpend(SL* s) { SLDataType* tmp = (SLDataType*)realloc(s->a, sizeof(SLDataType)*s->capacity * 2); if (tmp == NULL) { perror("realloc fail"); return; } s->a = tmp; s->capacity *= 2; printf("扩容成功\n"); } void Push_Back(SL* ps, SLDataType x) { if (ps->capacity == ps->size) { SLExpend(ps); } ps->a[ps->size++] = x; } void SLPrint(SL* ps) { for (int i = 0; i < ps->size; i++) { printf("%d ", ps->a[i]); } puts(""); } void Pop_Back(SL* ps) { if (ps->size == 0) { return; } ps->size--; } void Push_Front(SL* ps, SLDataType x) { if (ps->capacity == ps->size) { SLExpend(ps); } int end = ps->size; while (end) { ps->a[end] = ps->a[end - 1]; end--; } ps->a[0] = x; ps->size++; } void Pop_Front(SL* ps) { int pos = 1; while (pos < ps->size) { ps->a[pos - 1] = ps->a[pos]; pos++; } ps->size--; }
test.c文件
#include"SeqList.h" int main(void) { SL s; SeqInit(&s); Push_Back(&s, 1); Push_Back(&s, 2); Push_Back(&s, 8); Push_Back(&s, 8); Push_Front(&s, 100); Push_Front(&s, 99); Push_Front(&s, 98); SLPrint(&s); Pop_Front(&s); Pop_Front(&s); SLPrint(&s); printf("%d %d", s.capacity, s.size); return 0; }