静态链表
特性:
静态链表利用顺序表模拟链表
静态链表包含两条链表,一条为有效数据链表,一条为空闲节点链表
有效数据链表为带头结点的循环链表,且头结点在0号下标
空闲结点链表为带头结点的的循环链表,且头结点在1号下标
ps[1]相当于空闲链表的表头
ps[0]相当于有效链表的表头
初始化
void InitList(SNode* ps)//初始化
{
assert(ps != NULL);
if (ps == NULL)
{
return;
}
ps[0].next = 0;
for (int i = 1; i < MAXSIZE; i++)
{
ps[i].next = i + 1;
}
ps[MAXSIZE - 1].next = 1;
}
头插
bool InsertHead(SNode* ps,int val)//头插
{
assert(ps != NULL);
if (IsFull(ps))
{
return false;
}
//获取一个空闲结点
int p = ps[1].next;
//将空闲结点从空闲链表删除
ps[1].next = ps[p].next;
//放入数据
ps[p].data = val;
//将空闲结点插入有效链表
ps[p].next = ps[0].next;
ps[0].next = p;
return true;
}
尾插
if (IsFull(ps))
{
return false;
}
//获取一个空闲结点
int p = ps[1].next;
//将空闲结点从空闲链表删除
ps[1].next = ps[p].next;
//放入数据
ps[p].data = val;
//找尾巴
int q = 0;
while (ps[q].next != 0)
{
q = ps[q].next;
}
//将空闲结点插入有效链表
ps[p].next = ps[q].next;//等价于ps[p].next = 0
ps[q].next = p;//q = p;
//ps[q].next = 0;
return true;
获取长度
assert(ps != NULL);
int count = 0;
int p = 0;
while (ps[p].next != 0)
{
p = ps[p].next;
count++;
}
return count;
查找
int Search(SNode* ps, int key)//查找
{
assert(ps != NULL);
int p = ps[0].next;
//找key值
while (ps[p].data != key && ps[p].next!=0)
{
p = ps[p].next;
}
if (p != 0)
{
return ps[p].data;
}
else return -1;
}
获取值为val结点的前驱
int GetPrior(SNode* ps, int val)//获取值为val结点的前驱
{
assert(ps != NULL);
int p = 0;
while (ps[p].next != 0)
{
if (ps[ps[p].next].data == val)
{
return p;
}
p = ps[p].next;
}
}
删除值为val的结点
bool DelVal(SNode* ps, int val)//删除值为val的结点
{
assert(ps != NULL);
int p = 0;//p是值为val的结点
int q = 0;//q是值为val结点的前驱
while (ps[p].data != val && ps[p].next != 0)
{
q = p;
p = ps[p].next;
}
if (p == 0)
{
return false;
}
else//删除操作
{
ps[q].next = ps[p].next;
return true;
}
}
assert(ps != NULL);
int p = GetPrior(ps, val);//前驱结点
if (p == 0||p<0)
{
return false;
}
else//删除操作
{
int q = ps[p].next;
ps[p].next = ps[q].next;
//将结点添加到空闲链表中
ps[q].next = ps[1].next;
ps[1].next = q;
}
输出
void Show(SNode* ps)//输出
{
for (int p = ps[0].next; p != 0; p = ps[p].next)
{
printf("%d ", ps[p].data);
}
printf("\n");
}