顺序表是用一段 物理地址连续 的存储单元依次存储数据元素的线性结构,一般情况下采用数组存
储。在数组上完成数据的增删查改。
顺序表的实现
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int SLDataType;//重定义数据类型,方便以后可能改类型
typedef struct SeqList
{int* a;int size;//有效数据的个数int capacity;//容量大小
}SL;
void SLInit(SL*ps1);//初始化
void SLDestroy(SL*ps1);//销毁
void SLPrint(SL* ps1);//打印
void SLCheckcapacity(SL* ps1);//检查容量是否已经满了
void SLPushBack(SL* ps1, SLDataType x);//尾插
void SLPushFront(SL* ps1, SLDataType x);//头插
void SLPopBack(SL* ps1);//尾删
void SLPopFront(SL* ps1);//头删
void SLInSert(SL* ps1, int pos, SLDataType x);//任意位置插入;
void SLErase(SL* ps1, int pos);//任意位置删除
int SLFind(SL* ps1, SLDataType x);//void SLInit(SL* ps1)//初始化
{assert(ps1);ps1->a = NULL;ps1->size = 0;ps1->capacity = 0;
}
void SLDestroy(SL* ps1)//销毁
{assert(ps1);if (ps1->a != NULL){free(ps1->a);ps1->a = NULL;ps1->size = 0;ps1->capacity = 0;}
}
void SLPrint(SL* ps1)//打印
{assert(ps1);int i = 0;for (i = 0; i < ps1->size; i++){printf("%d ", ps1->a[i]);}printf("\n");
}
void SLCheckcapacity(SL* ps1)//检查空间是否满了
{assert(ps1);if (ps1->size == ps1->capacity)//空间满的情况下{SLDataType newcapacity = ps1->capacity == 0 ? 4 : 2 * ps1->capacity;//开始capacity为空的话给它一些空间SLDataType* tmp = (SLDataType*)realloc(ps1->a, sizeof(SLDataType) * newcapacity);if (tmp == NULL){perror("realloc");return;}ps1->a = tmp;ps1->capacity = newcapacity;}
}
void SLPushBack(SL * ps1, SLDataType x)//尾插
{assert(ps1);SLCheckcapacity(ps1);ps1->a[ps1->size] = x;//空间够的情况下,直接在size的位置尾插,ps1->size++;//size用完++;
}
void SLPushFront(SL* ps1, SLDataType x)//头插
{assert(ps1);SLCheckcapacity(ps1);int end = ps1->size - 1;while (end >= 0){ps1->a[end + 1] = ps1->a[end];end--;}ps1->a[0] = x;ps1->size++;
}
void SLPopBack(SL* ps1)//尾删
{assert(ps1->size>0);//为真就过,为假报错,防止size减到0还去减;ps1->size--;//减去一个size即删除最后一个数据;
}
void SLPopFront(SL* ps1)//头删
{assert(ps1->size > 0);int begin = 1;while (begin < ps1->size){ps1->a[begin-1] = ps1->a[begin];begin++;}ps1->size--;
}
void SLInSert(SL* ps1, int pos, SLDataType x)//任意位置插入;
{assert(ps1);assert(pos >= 0 && pos <= ps1->size);SLCheckcapacity(ps1);int end = ps1->size - 1;while (end >= pos){ps1->a[end + 1] = ps1->a[end];end--;}ps1->a[pos] = x;ps1->size++;
}
void SLErase(SL* ps1, int pos)//任意位置删除
{assert(ps1);assert(pos >= 0 && pos < ps1->size);int begin = pos + 1;while (begin < ps1->size){ps1->a[begin - 1] = ps1->a[begin];begin++;}ps1->size--;
}
int SLFind(SL* ps1, SLDataType x)//查找
{assert(ps1);int i = 0;for (i = 0; i < ps1->size; i++){if (ps1->a[i] == x){return i;}}return -1;
}
void test1()
{SL s1;SLInit(&s1);SLPushBack(&s1, 1);SLPushBack(&s1, 2);SLPushBack(&s1, 3);SLPushBack(&s1, 4);SLPushBack(&s1, 5);SLPrint(&s1);SLPushFront(&s1, 5);SLPrint(&s1);SLPopBack(&s1);SLPrint(&s1);SLPopFront(&s1);SLPrint(&s1);SLInSert(&s1, 2, 100);SLPrint(&s1);SLErase(&s1, 2);SLPrint(&s1);SLDestroy(&s1);
}
int main()
{test1();return 0;
}