1.静态顺序表的定义
//静态顺序表
typedef int DataType;
typedef struct SeqList
{
DataType data[MAX]; //顺序表中的数据
int sz;//表示当前顺序表有效数据的个数
}SeqList, *pSeqList;
2.初始化
//初始化
void InitSeqList(pSeqList ps)
{
assert(ps != NULL);
ps->sz = 0;
}
3.打印顺序表
//打印顺序表
void PrintSeqList(const pSeqList ps)
{
int i = 0;
assert(ps != NULL);
if (ps->sz == 0)
{
printf("顺序表为空\n");
return;
}
else
{
for (i = 0; i < ps->sz; i++)
{
printf("%d ", ps->data[i]);
}
printf("\n");
}
}
4.增->尾插法
void PushBack(pSeqList ps, DataType d)
{
assert(ps != NULL);
if (ps->sz == MAX)
{
printf("顺序表已满");
return;
}
else
{
ps->data[ps->sz] = d;
ps->sz++;
}
}
测试
void testPushBack()
{
PushBack(&Seq, 1);
PrintSeqList(&Seq);
PushBack(&Seq, 2);
PrintSeqList(&Seq);
PushBack(&Seq, 3);
PrintSeqList(&Seq);
PushBack(&Seq, 4);
PrintSeqList(&Seq);
PushBack(&Seq, 5);
PrintSeqList(&Seq);
}
5.增->头插法
void PushFront(pSeqList ps, DataType d)
{//头插
int i = 0;
assert(ps != NULL);
if (ps->sz == MAX)
{
printf("顺序表已满,无法插入\n");
return;
}
else
{
for (i = ps->sz; i > 0; i--)
{
ps->data[i] = ps->data[i-1];
}
ps->data[0] = d;
ps->sz++;
}
}
测试
void testPushFront()
{
PushFront(&Seq, 1);
PrintSeqList(&Seq);
PushFront(&Seq, 2);
PrintSeqList(&Seq);
PushFront(&Seq, 3);
PrintSeqList(&Seq);
PushFront(&Seq, 4);
PrintSeqList(&Seq);
PushFront(&Seq, 5);
PrintSeqList(&Seq);
}
6.增->指定位置插入
void Insert(pSeqList ps, int pos, DataType d)
{//指定位置插入
int i = 0;
assert(ps != NULL);
assert(ps->sz < MAX);
assert(pos >= 0 && pos <= ps->sz);
for (i = ps->sz - 1; i >= pos; i--)
{
ps->data[i + 1] = ps->data[i];
}
ps->data[pos] = d;
ps->sz++;
}
测试
void testPushBack()
{
PushBack(&Seq, 1);
PushBack(&Seq, 2);
PushBack(&Seq, 3);
PushBack(&Seq, 4);
PushBack(&Seq, 5);
PrintSeqList(&Seq);
PopBack(&Seq);
PrintSeqList(&Seq);
PopFront(&Seq);
PrintSeqList(&Seq);
Insert(&Seq, 2, 9);
PrintSeqList(&Seq);
}
7.删->尾删法
void PopBack(pSeqList ps)
{//尾删
assert(ps != NULL);
if (ps->sz == 0)
{
printf("顺序表为空,无法删除\n");
return;
}
else
{
ps->sz--;
}
}
测试
void testPushBack()
{
PushBack(&Seq, 1);
PushBack(&Seq, 2);
PushBack(&Seq, 3);
PushBack(&Seq, 4);
PushBack(&Seq, 5);
PrintSeqList(&Seq);
PopBack(&Seq);
PrintSeqList(&Seq);
}
8.删->头删
void PopFront(pSeqList ps)
{//头删
int i = 0;
assert(ps != NULL);
if (ps->sz == 0)
{
printf("顺序表为空 \n");
return;
}
else
{
for (i = 0; i < ps->sz-1; i++)
{
ps->data[i] = ps->data[i + 1];
}
ps->sz--;
}
}
测试
void testPushBack()
{
PushBack(&Seq, 1);
PushBack(&Seq, 2);
PushBack(&Seq, 3);
PushBack(&Seq, 4);
PushBack(&Seq, 5);
PrintSeqList(&Seq);
PopBack(&Seq);
PrintSeqList(&Seq);
PopFront(&Seq);
PrintSeqList(&Seq);
}
9.查找指定位置元素
int Find(pSeqList ps, DataType d)
{//查指定元素,找到了返回下标,没找到返回-1
int i = 0;
assert(ps != NULL);
for (i = 0; i < ps->sz; i++)
{
if (ps->data[i] == d)
return i;
}
return -1;
}
测试
void testP