SqList.h文件(该文件包含顺序表中一些函数的声明)
#pragma once
#include<stdio.h>
typedef int SLDataType;
#define INITIAL_CAPACITY 4
typedef struct SeqList
{
SLDataType* arr;
size_t size;
size_t capacity;
}SqList;
void SeqListInit(SqList* s);//初始化
void CheckCapacity(SqList* s);//检查capacity是否等于size(是否需要扩容
void SeqListPushBack(SqList* s, SLDataType x);//尾插法
void SeqListPopBack(SqList* s);//尾部消除
void SeqListPushFront(SqList* s, SLDataType x);//头插法
void SeqListPopFront(SqList* s);//头销毁
int SeqListFind(SqList* s, SLDataType x);//查找存储x的位置
void SeqListInsert(SqList* s, size_t pos, SLDataType x);//选取位置插入
void SeqListErase(SqList* s, size_t pos);//选取位置销毁
void SeqListDestroy(SqList* s);//顺序表销毁
void SeqListPrint(SqList* s);//顺序表打印
SqList.c(具体实现)
#include "SqList.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void SeqListInit(SqList* s)
{
s->arr = (SLDataType*)malloc(sizeof(SLDataType) * INITIAL_CAPACITY);
if (s->arr == NULL)
{
perror("Malloc Failed!");
return;
}
s->size = 0;
s->capacity = INITIAL_CAPACITY;
}
void CheckCapacity(SqList* s)
{
assert(s);
assert(s->arr);
if (s->capacity == s->size)
{
SLDataType *temp = (SLDataType*)realloc(s->arr, sizeof(SLDataType) * s->capacity * 2);
if (temp == NULL)
{
perror("Realloc Failed!");
return;
}
s->arr = temp;
s->capacity *= 2;
}
}
void SeqListPushBack(SqList* s, SLDataType x)
{
CheckCapacity(s);
s->arr[s->size++] = x;
}
void SeqListPopBack(SqList* s)
{
assert(s->arr);
assert(s->size > 0);
s->size--;
}
void SeqListPushFront(SqList* s, SLDataType x)
{
CheckCapacity(s);
size_t cur = s->size;
while (cur > 0)
{
s->arr[cur] = s->arr[cur - 1];
cur--;
}
s->arr[0] = x;
s->size++;
}
void SeqListPopFront(SqList* s)
{
assert(s);
assert(s->size>0);
size_t cur = 0;
while (cur != s->size - 1)
{
s->arr[cur++] = s->arr[cur+1];
}
s->size--;
}
int SeqListFind(SqList* s, SLDataType x)
{
assert(s);
int cur = 0;
while (cur != s->size)
{
if (s->arr[cur] == x)
return cur + 1;
else
cur++;
}
return -1;
}
void SeqListInsert(SqList* s, size_t pos, SLDataType x)
{
assert(s);
assert(pos >= 0 && pos <= s->size);
CheckCapacity(s);
size_t end = s->size-1;
while (end>=pos)
{
s->arr[end+1] = s->arr[end--];
}
s->arr[pos] = x;
s->size++;
}
void SeqListErase(SqList* s, size_t pos)
{
assert(s);
assert(pos >= 0 && pos <= s->size);
size_t cur = pos;
while (cur != s->size)
{
s->arr[cur++] = s->arr[cur + 1];
}
s->size--;
}
void SeqListDestroy(SqList* s)
{
free(s->arr);
s->arr = NULL;
s->size = s->capacity = 0;
}
void SeqListPrint(SqList* s)
{
assert(s->size);
for (size_t i = 0; i < s->size; ++i)
{
printf("%d ", s->arr[i]);
}
printf("\n");
}
顺序表的一些缺点
1.在中间或者头部插入的时候,时间复杂度为O(N)
2.扩容的时候需要进行申请空间,势必会发生将旧空间内容转移到新空间去,并且释放旧空间,这增大了消耗。
3.扩容一般都是2倍扩容,这势必会有空间的浪费。