作者:逃跑的骨拉拉gf_761 | 来源:互联网 | 2023-05-17 08:31
静态链表:结构体变量中包含数据域和游标域typedefstructNode{ELEM_TYPEmdata;数据域intcursor;游标}SNode;静态链表:1.数组的下标为0的
静态链表:
结构体变量中包含数据域和游标域
typedef struct Node
{
ELEM_TYPE mdata;//数据域
int cursor;//游标
}SNode;
静态链表:
1.数组的下标为0的元素的游标域存放的是未使用链表的第一个节点的下标。
2.数组的最后一个元素(SLIST_SIZE-1)存放的是第一个有数据值得元素的下标。
3.最后一个元素相当于单链表的头结点。
具体代码如下:
//=============SList.h============
#define SLIST_SIZE 22
typedef int ELEM_TYPE;
typedef struct Node
{
ELEM_TYPE mdata;
int cursor;
}SNode;
typedef struct List
{
SNode node[SLIST_SIZE];
}SList,*PSList;
void init(PSList psl);//初始化
static int isFull(PSList psl);
void insertTail(PSList psl,ELEM_TYPE val);//尾插
void insertHead(PSList psl,ELEM_TYPE val);
int isEmpty(PSList psl);
void DeleteKey(PSList psl,int val);
void Show(PSList psl);
void Clear(PSList psl);
void Destroyed(PSList psl);
//=============SList.cpp===========
# include
# include "SList.h"
void init(PSList psl)//初始化
{
if(psl == NULL)
{
return;
}
int i=0;
for(i;inode[i].cursor = i+1;
}
psl->node[i++].cursor = -1;
psl->node[i].cursor=-1;
}
static int isFull(PSList psl)
{
return psl->node[0].cursor ==-1;
}
void insertTail(PSList psl,ELEM_TYPE val)
{
if(psl == NULL||isFull(psl))
{
return;
}
int index = psl->node[0].cursor;
psl->node[0].cursor = psl->node[index].cursor;
psl->node[index].mdata =val;
psl->node[index].cursor=-1;
int lastindex=SLIST_SIZE-1;
while(psl->node[lastindex].cursor != -1)
{
lastindex=psl->node[lastindex].cursor ;
}
psl->node[lastindex].cursor =index;
}
void insertHead(PSList psl,ELEM_TYPE val)
{
if(psl == NULL||isFull(psl))
{
return;
}
int index = psl->node[0].cursor;
psl->node[0].cursor = psl->node[index].cursor;
psl->node[index].mdata =val;
psl->node[index].cursor=psl->node[SLIST_SIZE-1].cursor;
psl->node[SLIST_SIZE-1].cursor=index;
}
int isEmpty(PSList psl)
{
return psl->node[SLIST_SIZE-1].cursor==-1;
}
void DeleteKey(PSList psl,int val)
{
if(psl==NULL||isEmpty(psl))
{
return;
}
int index = SLIST_SIZE -1;
int nextindex =psl->node[index].cursor ;
while(nextindex !=-1)
{
if(psl->node[nextindex].mdata == val)
{
break;
}
index = nextindex;
nextindex = psl->node[nextindex].cursor;
}
if(nextindex == -1)
{
return;
}
psl->node[index].cursor = psl->node[nextindex].cursor;
psl->node[nextindex].cursor =psl->node[0].cursor;
psl->node[0].cursor=nextindex;
}
void Show(PSList psl)
{
if(psl==NULL)
{
return;
}
int index = psl->node[SLIST_SIZE-1].cursor ;
while(index!=-1)
{
printf("%d ",psl->node[index].mdata);
index =psl->node[index].cursor;
}
printf("\n");
}
void Clear(PSList psl)
{
if(psl==NULL)
{
return;
}
int i=0;
for(i;inode[i].cursor=i+1;
}
psl->node[i++].cursor =-1;
psl->node[i].cursor=-1;
}
void Destroyed(PSList psl)
{
Clear(psl);
}
//==============main.cpp========
# include "SList.h"
int main()
{
SList sl;
init(&sl);
int i=0;
for(i;i<10;i++)
{
insertHead(&sl,i+1);
}
Show(&sl);
DeleteKey(&sl,4);
for(i;i<20;i++)
{
insertTail(&sl,i+1);
}
Show(&sl);
Clear(&sl);
Destroyed(&sl);
return 0;
}
输出结果: