数据结构是计算机存储、组织数据的方式。采用适当的数据结构可以提高计算机的运行或存储效率。
在计算机中,数据按照一定的线性结构存储,这种数据结构被称为线性表。线性表是被广泛应用的数据结构,常见的线性表有顺序表、链表、队列、栈等等。
注意:线性表在逻辑上是线性结构,但物理表示上不一定连续存储,一般以数组或链式结构表示。
顺序表是用一段物理地址连续的存储单元依次存储各个元素的数据结构。要实现物理地址连续可以采用数组表示顺序表;而顺序表与数组又有不同:顺序表存储数据必须是依次连续存储,如下图;
故而顺序表的表示可以是这样:
//静态顺序表
#define N 10
typedef struct SeqList
{
int a[N];
int size;
}SL;
静态顺序表的大小固定了,为了能更方便的存储数据,有了动态顺序表:
//动态顺序表
typedef int SLDataType;
typedef struct SeqList
{
SLDataType* a;
int size; //顺序表数据个数
int capacity; //顺序表大小
}SL;
动态顺序表的接口:
//顺序表初始化、销毁
void SLInit(SL* ps);
void SLDesdroy(SL* ps);
//尾插尾删
void SLPushBack(SL* ps, int x);
void SLPopBack(SL* ps);
//打印顺序表
void SLPrint(SL* ps);
//头插头删
void SLPushFront(SL* ps, int x);
void SLPopFront(SL* ps);
//任意位置插入删除
void SLInsert(SL* ps, int pos, int x);
void SLErase(SL* ps, int pos);
//顺序表查找,找到则返回位置下标,否则返回-1
int SLFind(SL* ps, int x);
接口实现:
//顺序表初始化
void SLInit(SL* ps)
{
assert(ps);
ps->a = NULL;
ps->size = 0;
ps->capacity = 0;
}
//顺序表销毁
void SLDesdroy(SL* ps)
{
assert(ps);
if (ps->a != NULL)
{
free(ps->a);
ps->a = NULL;
ps->size = 0;
ps->capacity = 0;
}
}
//顺序表容量的检查
void SLExpansion(SL* ps)
{
assert(ps);
if (ps->size == ps->capacity)
{
int newCapacity = ps->size == 0 ? 4 : ps->capacity * 2;
SLDataType* tmp = (SLDataType*)realloc(ps->a, newCapacity * sizeof(SLDataType));
if (tmp)
{
ps->a = tmp;
ps->capacity = newCapacity;
}
}
}
//顺序表尾插
void SLPushBack(SL* ps, int x)
{
assert(ps);
SLExpansion(ps);
ps->a[ps->size] = x;
ps->size++;
}
//顺序表尾删
void SLPopBack(SL* ps)
{
//判断顺序表是否为空
/*if (ps->size == 0)
{
printf("顺序表为空\n");
return;
}*/
assert(ps);
assert(ps->size > 0);
ps->size--;
}
//顺序表打印
void SLPrint(SL* ps)
{
assert(ps);
for (int i = 0; i < ps->size; i++)
{
printf("%d ", ps->a[i]);
}
printf("\n");
}
//顺序表头插
void SLPushFront(SL* ps, int x)
{
assert(ps);
//扩容
SLExpansion(ps);
/*for (int i = 0; i < ps->size; i++)
{
ps->a[ps->size-i] = ps->a[ps->size - i-1];
}*/
for (int end = ps->size; end > 0; end--)
{
ps->a[end] = ps->a[end - 1];
}
ps->a[0] = x;
ps->size++;
}
//顺序表头删
void SLPopFront(SL* ps)
{
assert(ps);
assert(ps->size > 0);
if (ps->size == 1)
{
ps->size--;
return;
}
for (int begin = 0; begin < ps->size - 1; begin++)
{
ps->a[begin] = ps->a[begin + 1];
}
ps->size--;
}
//任意位置插入
void SLInsert(SL* ps, int pos, int x)
{
assert(ps);
assert(pos <= ps->size);
if (pos == ps->size)
{
SLPushBack(ps, x);
}
else
{
SLExpansion(ps);
for (int end = ps->size; end > pos; end--)
{
ps->a[end] = ps->a[end - 1];
}
ps->a[pos] = x;
ps->size++;
}
}
//任意位置删除
void SLErase(SL* ps, int pos)
{
assert(ps);
if (pos == ps->size)
{
SLPopBack(ps);
}
else
{
for (int begin = pos; begin < ps->size - 1; begin++)
{
ps->a[begin] = ps->a[begin + 1];
}
ps->size--;
}
}
//顺序表查找
int SLFind(SL* ps, int x)
{
assert(ps);
for (int i = 0; i < ps->size; i++)
{
if (ps->a[i] == x)
{
return i;
}
}
return -1;
}
从顺序表的增删查改可以看出,顺序表尾插尾删的时间复杂度是O(1),头插头删的时间复杂度是O(N),因此,顺序表更适用于尾插尾删。