顺序表不仅在逻辑上是连续存储的,物理上也是连续存储的
首先我们用结构体定义顺序表的类型
typedef int ElemType;
#define SEQLEN 10
typedef struct _SqList
{
ElemType data[SEQLEN]; // 存储数据元素的连续空间
int count; // 记录有效元素个数的变量
}SqList, *pSqList;
其次我们把接下来需要用到的函数写出来
//判断是否为满
static bool IsFull(pSqList sq)
{
return sq->count == SEQLEN;
}
static bool IsEmpty(pSqList sq)
{
return sq->count == 0;
}
1.初始化
bool Init_SqList(pSqList sq)
{
assert(NULL != sq);
if (NULL == sq) return false;
sq->count = 0; // 初始化顺序表,表示顺序中没有存储任何有效数据
return true;
}
2.插入(分为头插尾插位置插)
我们可以先解决位置插,然后调用解决头插尾插
其思路为:
1.判断顺序表是否为满
2.判断插入位置是否合法
3.移动后面元素,空出插入位置
4.插入内容至位置
5.顺序表数目+1
(1)位置插
bool Insert_Pos(pSqList sq, ElemType val, int pos)
{
//1、 判断顺序表是否为满
if (IsFull(sq)) return false;
//2、 判断pos位置是否合法
if (pos < 0 || pos >sq->count) return false;
//3、 移动pos后面的所有元素,将pos位置空出来
int i = sq->count;
while (i > pos)
{
sq->data[i] = sq->data[i - 1];
i--;
}
//4、 将val插入到pos位置
sq->data[pos]=val;
//5、 将count+1
sq->count++;
return true;
}
(2)头插
bool Insert_Head(pSqList sq, ElemType val)
{
return Insert_Pos(sq,val,0);
}
(3)尾插
bool Insert_Tail(pSqList sq, ElemType val)
{
return Insert_Pos(sq,val,0);
}
2.删除(分为头删尾删位置删以及特殊的删除重复元素)
思路类似于插入:
1.判断顺序表是否为空
2.判断删除位置是否合法
3.移动后面元素往前
5.顺序表数目-1
(1)位置删
bool Delete_Pos(pSqList sq, int pos)
{
//1.判断顺序表是否为空
if(IsEmpty(sq)) return false;
//2.判断pos位置是否合法
if(pos<0 || pos >=sq->count) return false;
//3.将pos以及后面的所有元素向前移动一位
while(pos <sq->count - 1)
{
sq->data[pos] = sq->data[pos+1];
pos++
}
//4.将count-1
sq->count--;
}
(2)头删
bool Delete_Head(pSqList sq)
{
return Delete_Pos(sq,0);
}
(3)尾删
bool Delete_Tail(pSqList sq)
{
return Delete_Pos(sq,sq->count - 1);
}
(4)重复元素的情况
void Delete_Element(pSqList sq, ElemType val)
{
int i = 0, j = 0;
for (; j < sq->count;)
{
if (sq->data[j] == val)
{
j++;
}
if (sq->data[j] != val) // 为了防止有连续需要删除的元素
{
if (i != j)
{
sq->data[i] = sq->data[j];
}
i++;
j++;
}
}
sq->count -= (j - i);
}
3.查找(按位置找和按内容找)
(1)按位置找
bool FindElement_Pos(pSqList sq, int pos, ElemType *result)
{
if (pos >= sq->count)
{
return false;
}
*result = sq->data[pos];
return true;
}
(2)按内容找
int FindPos_Locate(pSqList sq, ElemType val,
bool(*compare)(ElemType, ElemType)) // 函数指针 比较函数
{
for (int i = 0; i < sq->count; ++i)
{
if (compare(val, sq->data[i]))
{
return i;
}
}
return -1;
}
4.逆置
void Reverse_SqList(pSqList sq, void (*Swap)(ElemType *a, ElemType *b))
{
int i = 0;
int j = sq->count - 1; // i j 是下标 count是元素的个数
for (; i < j; i++, j--)
{
Swap(&sq->data[i], &sq->data[j]);
}
}