赞
踩
线性表是(linear list)n个具有相同特性的数据元素的有限队列。线性表是一种在实际广泛应用的的数据结构,常见的线性表:顺序表,链表,栈,队列,字符串。。。
线性表在逻辑结构上是连续的。但在物理结构上不一定连续,线性表在物理上存储时,通常以数组和链表的形式存储。
概念:顺序表是用一段物理地址连续的存储单元一次存储数据元素的线性结构,一般采用与数组类似的存储方式。
顺序表与数组的区别
顺序表的底层是数组,对数组进行封装,实现了增删查改等接口
概念:使用定长数组进行存储数据的结构
//静态顺序表
typedef int SLDataType;
#define N 7
typedef struct SeqList
{
SLDataType arr[N];// 定长数组
int size; //有效数据个数
}SL;
//动态顺序表
typedef int SLDataType;
typedef struct SeqList
{
SLDataType* arr; //动态数组
int size; //有效数据个数
int capacity; //空间大小
}SL;
// 初始化和销毁void SLInit(SL* ps);void SLDestroy(SL* ps);void SLPrint(SL* ps);// 扩容void SLCheckCapacity(SL* ps);// 头部插⼊删除 / 尾部插⼊删除void SLPushBack(SL* ps, SLDataType x);void SLPopBack(SL* ps);void SLPushFront(SL* ps, SLDataType x);void SLPopFront(SL* ps);// 指定位置之前插⼊ / 删除数据void SLInsert(SL* ps, int pos, SLDataType x);void SLErase(SL* ps, int pos);//查找int SLFind(SL* ps, SLDataType x);
- // 初始化
- void SeqListInit(SL* ps)
- {
- ps->arr = NULL;
- ps->capacity = ps->size = 0;
- }
-
- //销毁
- void SeqListDestroy(SL* ps)
- {
- if (ps->arr!=NULL)
- free(ps->arr);
- ps->arr = NULL;
- free(ps->capacity & ps->size);
- ps->capacity = ps->size = 0;
- }
- //打印
- void SeqListPrint(SL* ps)
- {
- for (int i = 0; i < ps->size; i++)
- {
- printf("%d->", ps->arr[i]);
- }
- printf("NULL\n");
- }

- void SLcheckCapacity(SL* ps)
- {
- //插入之前判断空间是否足够
- //三目操作符
- if (ps->capacity == ps->size)
- {
- int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
- SLDateType* tmp = (SLDateType*)realloc(ps->arr, sizeof(SLDateType) * newcapacity);
- if (tmp == NULL)
- {
- printf("realloc fail!\n");
- exit(1);
- }
- ps->arr = tmp;
- ps->capacity = newcapacity;
- }
- }

- //头插
- void SeqListPushFront(SL* ps, SLDateType x)
- {
- SLcheckCapacity(ps);
- for (int i = ps->size;i>0; i--)
- ps->arr[i] = ps->arr[i - 1];
- ps->arr[0] = x;
- ps->size++;
- }
-
- //头删
- void SeqListPopFront(SL* ps)
- {
- assert(ps);
- assert(ps->size);
- for (int i = 0; i < ps->size-1; i++)
- ps->arr[i] = ps->arr[i + 1];
- ps->size--;
- }
- //尾删
- void SeqListPopBack(SL* ps)
- {
- assert(ps);
- assert(ps->size);
- ps->size--;
- }
- //尾插
- void SeqListPushBack(SL* ps, SLDateType x)
- {
- assert(ps);
- SLcheckCapacity(ps);//检查容量
- ps->arr[ps->size] = x;
- ps->size++;
- }

- // 顺序表在pos位置插入x
- void SeqListInsert(SL* ps, int pos, SLDateType x)
- {
- SLcheckCapacity(ps);
- assert(ps);
- assert(pos >= 0 && pos <= ps->size);
- for (int i = ps->size; i > pos; i--)
- ps->arr[i] = ps->arr[i - 1];
- ps->arr[pos] = x;
- ps->size++;
- }
-
- // 顺序表删除pos位置的值
- void SeqListErase(SL* ps, int pos)
- {
- assert(ps);
- assert(ps->size);
- for (int i = pos; i<ps->size-1; i++)
- {
- ps->arr[i] = ps->arr[i + 1];
- }
- ps->size--;
- }

- // 顺序表查找
- int SeqListFind(SL* ps, SLDateType x)
- {
- assert(ps);
- for (int i = 0; i < ps->size; i++)
- {
- if (x == ps->arr[i])
- return i;
- }
- return -1;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。