赞
踩
顺序表是一种线性表的存储结构,它使用一组地址连续的存储单元依次存储线性表的数据元素。在顺序表中,逻辑上相邻的元素在物理存储上也相邻,通常采用数组来实现这种存储方式。
顺序表格的特点:
顺序表简单介绍:
准备工作;
- #include <stdlib.h>
- #include <assert.h>
-
- typedef int SLDataType;
-
- #define Initcapacity 3
-
- typedef struct SeqList
- {
- SLDataType* a;
- int size;
- int capacity;
- }SL;
定义:
结构体 SL;重定义int类型;包含所需要的头文件
- //初始化顺序表
- void InitSL(SL* ps)
- {
- assert(ps);
- ps->a = (SLDataType*)malloc(sizeof(SLDataType) * Initcapacity);
- if (ps->a == NULL)
- {
- perror("malloc fail");
- return;
- }
- ps->capacity = Initcapacity;
- ps->size = 0;
- }
- //空间销毁
- void SLDestory(SL* ps)
- {
- assert(ps);
- free(ps->a);
- ps->a = NULL;
- ps->size = 0;
- ps->capacity = 0;
- }
- //检查容量并增加
- void CheckCapacity(SL* ps)
- {
- if (ps->size == ps->capacity)
- {
- SLDataType* tmp = (SLDataType*)realloc(ps->a, sizeof(SLDataType) * ps->capacity * 2);
- if (tmp == NULL)
- {
- perror("realloc fail");
- return;
- }
- ps->capacity *= 2;
- ps->a = tmp;
- }
- }
- //头插
- void SeqListPushFront(SL* ps, SLDataType x)
- {
- assert(ps);
- CheckCapacity(ps);
- int end = ps->size - 1;
- if (ps->size > 0)
- {
- while (end >= 0)
- {
- ps->a[end + 1] = ps->a[end];
- end--;
- }
- }
- ps->a[0] = x;
- ps->size++;
- }
- void SeqListPushBack(SL* ps, SLDataType x)
- {
- assert(ps);
-
- CheckCapacity(ps);
-
- ps->a[ps->size] = x;
- ps->size++;
- }
- // insert 元素
- void SeqListInsert(SL* ps, int pos, SLDataType x)
- {
- assert(ps);
- assert(pos >= 0 && pos < ps->size - 1);
- CheckCapacity(ps);
- int end = ps->size - 1;
- while (end >= pos)
- {
- ps->a[end + 1] = ps->a[end + 1];
- end--;
- }
- ps->a[pos] = x;
- }
- // 头删
- void SeqListPopFront(SL* ps)
- {
- assert(ps);
- assert(ps->size > 0);
- int begin = 1;
- while (begin < ps->size)
- {
- ps->a[begin - 1] = ps->a[begin];
- begin++;
- }
- ps->size--;
-
- }
- //尾删
- void SeqListPopBack(SL* ps)
- {
- assert(ps);
- assert(ps->size > 0);
- ps->size--;
-
- }
- //指定位置删元素
- void SeqListErase(SL* ps, int pos)
- {
- assert(ps);
- assert(ps >= 0 && pos < ps->size);
- int begin = pos - 1;
- while (begin < ps->size - 1)
- {
- ps->a[begin] = ps->a[begin + 1];
- begin++;
- }
- ps->size--;
- }
- //暴力查找
- int SeqListFind(SL* ps, SLDataType x)
- {
- assert(ps);
- int pos = 0;
- for (int i = 0; i < ps->size; i++)
- {
- if (ps->a[i] == x)
- {
- pos = i;
- break;
- }
- }
-
- return pos;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。