一、顺序表
#include<stdio.h> #include<stdlib.h> #include<errno.h> #pragma once //防止头文件被多次包含 #define N 100 typedef int SLDataType; //静态顺序表 typedef struct SeqList { int* a; int size; //表示数组中存储了多少个数据 int capacity; //数组实际能存数据的空间容量是多大 }SL; //接口函数--命名风格是跟着STL走的,方便后续学习STL //void SeqListInit(SL * ps); //void SeqListPushBack(SL* ps, SLDataType x); //void SeqListPopBack(SL* ps); //void SeqListPushFront(SL* ps, SLDataType x); //void SeqListPopFront(SL* ps); //初始化 void SeqListInit(SL* ps) { ps->a = NULL; ps->size = 0; ps->capacity = 0; } //尾插法 void SeqListPushBack(SL* ps, SLDataType x) { //如果没有空间或者空间不足,扩容 int newcapacity = 0; if (ps->size == ps->capacity) { if (ps->capacity == 0) newcapacity = 4; else newcapacity = ps->capacity * 2; SLDataType* tmp = (SLDataType*)realloc(ps->a, newcapacity * sizeof(SLDataType)); if (tmp == NULL) { perror("SeqListPushBack"); exit(-1);//异常则退出 } ps->a = tmp; ps->capacity = newcapacity; } ps->a[ps->size] = x; ps->size++; } void SeqListPrint(SL* ps) { int i = 0; for (i = 0;i < ps->size;i++) printf("%d ", ps->a[i]); printf("\n"); } void TestSeqList1() { SL s1; SeqListInit(&s1); SeqListPushBack(&s1, 1); SeqListPushBack(&s1, 2); SeqListPushBack(&s1, 3); SeqListPushBack(&s1, 4); SeqListPushBack(&s1, 5); SeqListPushBack(&s1, 6); SeqListPrint(&s1); } int main() { TestSeqList1(); return 0; }