数据结构
一.顺序表
1.定长顺序表
分为‘数组’和‘顺序表’两种。
#pragma once//预防头文件被重复引用,若被重复引用则自动忽略
定义 定长顺序表结构体
#pragma once//
typedef struct SQList //定长顺序表
{
int length;
int elem[10];
}SQList, * PSQList;
初始化
void InitSqlist(PSQList ps)//初始化
{
assert(ps!= NULL);
ps->length = 0;
}
在pos位置插入val
bool Insert(PSQList ps, int pos, int val)//在pos位置插入val
{
assert(ps != NULL);
if (ps == NULL)
{
return -1;
}
//把数据后移一位
for (int i = ps->length - 1; i >= pos; i--)
{
ps->elem[i + 1] = ps->elem[i];
}
//把val赋值给数组的pos位置
ps->elem[pos] = val;
ps->length++;
return true;
}
判空
bool IsEmpty(PSQList ps)//判空
{
assert(ps != NULL);
return ps->length == 0;
}
查找第一个key值,并返回找到下标,没找到返回-1
int Search(PSQList ps, int key)//查找第一个key值,并返回找到下标,没找到返回-1
{
assert(ps != NULL);
for (int i = 0; i < ps->length; i++)
{
if (ps->elem[i] == key)
{
return i+1;
}
}
return -1;
}
判满
static bool IsFull(PSQList ps)
{
return ps->length == 10;
}
删除pos位置的数据
bool DelPos(PSQList ps, int pos)//删除pos位置的数据
{
assert(ps != NULL);
if (pos < 0&&pos>=ps->length)
{
return false;
}
for (int i = pos-1; i < ps->length-1; i++)//把数据前移一位
{
ps->elem[i] = ps->elem[i + 1];
}
ps->length--;
return true;
}
删除第一个val的数值
bool DelVal(PSQList ps, int val)//删除第一个val的数值
{
assert(ps != NULL);
int i = Search(ps,val);
if (i < 0)
{
return false;
}
return DelPos(ps, i);
}
得到key的前驱下标,不存在返回-1
int GetPrior(PSQList ps, int key)//得到key的前驱下标,不存在返回-1
{
assert(ps != NULL);
int i = Search(ps, key);
if (i <= 0)//当i==0时返回数值也是-1
{
return -1;
}
else return i - 1;
}
得到key的后继下标,不存在返回-1
int GetNext(PSQList ps, int key)//得到key的后继下标,不存在返回-1
{
assert(ps != NULL);
int i = Search(ps, key);
if (i <0||i==ps->length)//当i等于最后一位元素位置,无后继
{
return -1;
}
else return i + 1;
}
输出
void Show(PSQList ps)//输出
{
assert(ps != NULL);
for (int i = 0; i < ps->length; i++)
{
printf("%d ", ps->elem[i]);
}
}
清空数据
void Clear(PSQList ps)//清空数据
{
assert(ps != NULL);
ps->length = 0;
}