每一个不曾起舞的日子,都是对生命的辜负。
初阶数据结构之动态顺序表实现
三、实现具体功能代码页(SeqList.c)
#define _CRT_SECURE_NO_WARNINGS 1 #include"SeqList.h" #include<assert.h> void SeqListInit(SeqList* pq)//初始化 { assert(pq);//断言,判断是否可以执行1/0 pq->a = NULL; pq->size = 0; pq->capacity = 0; } void SeqListDestory(SeqList* pq) { assert(pq); free(pq->a); pq->a = NULL; pq->capacity = pq->size = 0; } void SeqCheckCapacity(SeqList* pq) { if (pq->size == pq->capacity)//满了,需要增容 { int newcapacity = pq->capacity == 0 ? 4 : pq->capacity * 2; //SeqDataType* newA = malloc(sizeof(SeqDataType) * newcapacity); SeqDataType* newA =realloc(pq->a,sizeof(SeqDataType)* newcapacity);//或者直接扩容 if (newA == NULL) { printf("realloc fail\n"); exit(-1); } pq->a = newA; pq->capacity = newcapacity; } } void SeqListPushBack(SeqList* pq, SeqDataType x) { assert(pq); SeqCheckCapacity(pq); pq->a[pq->size] = x; pq->size++; } void SeqListPrint(SeqList* pq) { assert(pq); for (int i = 0; i < pq->size; ++i) { printf("%d ", pq->a[i]); } printf("\n"); } void SeqListPushFront(SeqList* pq, SeqDataType x) { assert(pq); SeqCheckCapacity(pq); int end = pq->size - 1; while (end >= 0) { pq->a[end + 1] = pq->a[end]; end--; } pq->a[0] = x; pq->size++; } void SeqListPopBack(SeqList* pq) { assert(pq); assert(pq->size > 0); --pq->size; } void SeqListPopFront(SeqList* pq) { assert(pq); for (int i = 0; i < pq->size - 1; i++) { pq->a[i] = pq->a[i + 1]; } if(pq->size) pq->size--; }
三(补).test.c主函数代码页
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> #include"SeqList.h" void TestSeqList1() { SeqList s; SeqListInit(&s);//ʼ SeqListPushBack(&s, 1); SeqListPushBack(&s, 2); SeqListPushBack(&s, 3); SeqListPushBack(&s, 4); SeqListPushBack(&s, 5); SeqListPushFront(&s, 0); SeqListPushFront(&s, 0); SeqListPushFront(&s, 0); SeqListPushFront(&s, 0); SeqListPrint(&s); SeqListPopBack(&s); SeqListPrint(&s); SeqListPopBack(&s); SeqListPrint(&s); SeqListDestory(&s);// } int main() { TestSeqList1(); return 0; }
四.总结
当然,最详细的完整代码在这里:链接: 顺序表完整代码