顺序表
本次博客我们将介绍数据结构基础。数据结构大致分为顺序结构,树形结构与图。本次所要介绍的顺序表属于顺序结构。
顺序表底层为数组,相对于其他顺序结构优点在于查找方便,可是当我们进行删除操作时较为复杂。利用顺序表我们可以完成通讯录等小型项目。
顺序表:用一段地址连续的存储单元依次存储数据元素的线性结构地址连续的空间,一般情况下采用数组,但数组有静态数组和动态数组,所以顺序表分为:静态顺序表和动态顺序。
以下为顺序表的代码实现。
typedef int DataType;//定义顺序表里数据类型 typedef struct SeqList//定义顺序表结构体 { DataType *a; size_t size;//有效数据数量 }SeqList; #define first 10//先给10个单位
首先我们需要初始化顺序表
void SeqInit(SeqList* pSeq) { assert(pSeq); pSeq->size = 0; pSeq->a = (DataType*)malloc(sizeof(SeqList)*first); if (pSeq->a == NULL) { return; } memset(pSeq->a, 0, sizeof(SeqList)*first); }然后我们需要有将顺序表每个元素打印出来的函数
void SeqPrint(SeqList* pSeq) { assert(pSeq); if (pSeq->size <= 0) printf("数据数量不足\n"); else { int i = 0; for (;i < (int)pSeq->size;i++) { printf("%d",pSeq->a[i]); } } }接下来当我们完成所有操作时,还需要销毁顺序表
void SeqDestory(SeqList* pSeq) { free(pSeq->a); pSeq->a == NULL; }尾部增加数据
void SeqPushBack(SeqList* pSeq, DataType x) { assert(pSeq); if (pSeq->size >= first) printf("数据已满,不能在插入数据\n"); else pSeq->a[pSeq->size] = x; pSeq->size++ ; }尾部删除数据
void SeqPopBack(SeqList* pSeq) { assert(pSeq); if (pSeq->size == 0) { printf("顺序表为空\n"); } else { pSeq->size--; } }头部插入数据
void SeqPushFront(SeqList* pSeq, DataType x) { assert(pSeq); int i; if (pSeq->size >= first) { printf("顺序表已满\n"); } for (i = pSeq->size;i > 0;i--) { pSeq->a[i] = pSeq->a[i-1]; } pSeq->a[0] = x; pSeq->size++; }头部删除数据
void SeqPopFront(SeqList* pSeq) { assert(pSeq); if (pSeq->size == 0) { printf("顺序表为空\n"); } else { int i = 1; for (i =1;i <pSeq->size;i++) { pSeq->a[i - 1] = pSeq->a[i]; } pSeq->size--; } }在pos位置插入数据
void SeqInsert(SeqList* pSeq, size_t pos, DataType x) { assert(pSeq); if (pSeq->size >= first) { printf("顺序表已满\n"); } else { int i; for (i = pSeq->size;i > pos;i--) { pSeq->a[i] = pSeq->a[i - 1]; } pSeq->a[pos] = x; pSeq->size++; } }在pos位置删除数据
void SeqErase(SeqList* pSeq, size_t pos) { assert(pSeq); int i; if (pSeq->size == 0) { printf("顺序表为空\n"); } else { for (i = pos;i <=pSeq->size;i++) pSeq->a[i - 1] = pSeq->a[i]; } pSeq->size--; }查找数据
int SeqFind(SeqList* pSeq, DataType x) { assert(pSeq); int i; for (i = 0;i < pSeq->size;i++) { if (pSeq->a[i] == x) { return i-1; } } }冒泡排序
void BubbleSort(SeqList* pSeq) { assert(pSeq); DataType data; int i, j; for(i=0;i<pSeq->size;i++) for (j = 0;j < i;j++) { if (pSeq->a[j] > pSeq->a[i]) { data = pSeq->a[i]; pSeq->a[i] = pSeq->a[j]; pSeq->a[j] = data; } } }
到此,我们已经完成了顺序表的基础操作,包括建立顺序表,初始化以及增删改查。