静态线性表用于不存在指针的语言当中,在C当中可以作为一种积累
静态链表的物理结构为数组
第一个数组元素的cursor存储空闲空间的首地址
最后一个数组元素的cursor存储第一个实际数据的首地址,相当于头结点
#include <stdio.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 1000 /* 存储空间初始分配量 */
typedef int Status; /* Status是函数的类型,其值是函数结果状态代码,如OK等 */
typedef char ElemType; /* ElemType类型根据实际情况而定,这里假设为char */
//线性表的静态链表存储结构
typedef struct {
ElemType data;
int cursor;
}Node,StaticLinkList[MAXSIZE];
Status InitList(StaticLinkList L){
//建立数组元素0至的前后关系
for(int i = 0; i < MAXSIZE - 1; i++){
L[i].cursor = i + 1;
}
//将数组最后一个元素的cursor指向数组首元素
L[MAXSIZE-1].cursor = 0;
return OK;
}
/*
* return:数组分配空间的下标
*/
int Malloc_SSL(StaticLinkList L){
int locate = L[0].cursor;//空闲元素的下标
if(locate){
//非零表示还有空间可以分配
L[0].cursor = L[locate].cursor;
}
return locate;
}
void Free_SSL(StaticLinkList L,int k){
//将第一个元素的cursor赋给要删除的元素的cursor
L[k].cursor = L[0].cursor;
//将要删除的元素作为空闲空间的第一个元素
L[0].cursor = k;
}
int ListLength(StaticLinkList L){
int length = 0;
int currentPos = MAXSIZE-1;
while(L[currentPos].cursor){
length++;
//指向下一个元素的下标
currentPos = L[currentPos].cursor;
}
return length;
}
Status ListInsert(StaticLinkList L, int i, ElemType e){
if(i<1 || i>ListLength(L)+1){
printf("Insert a illegal position");
return ERROR;
}
//获取空闲元素的下标
int free_pos = Malloc_SSL(L);
printf("Insert free_pos = %d\n",free_pos);
if(free_pos){
int currentPos = MAXSIZE-1;
//定位到第i-1个元素
for(int j = 1; j <= i - 1; j++){
currentPos = L[currentPos].cursor;
}
L[free_pos].cursor = L[currentPos].cursor;
L[currentPos].cursor = free_pos;
L[free_pos].data = e;
return OK;
}
return ERROR;
}
Status ListDelete(StaticLinkList L,int i){
if(i<1 || i>ListLength(L)){
printf("Insert a illegal position");
return ERROR;
}
int currentPos = MAXSIZE-1;
//定位到第i-1个元素
for(int j = 1; j <= i - 1; j++){
currentPos = L[currentPos].cursor;
}
//第i个元素的位置
int iPostion = L[currentPos].cursor;
L[currentPos].cursor = L[iPostion].cursor;
Free_SSL(L,iPostion);
return OK;
}
Status ListPrint(StaticLinkList L)
{
int currentPos = L[MAXSIZE-1].cursor;
int count = 1;
while(currentPos)
{
printf("%d:%c\n",count++,L[currentPos].data);
currentPos = L[currentPos].cursor;
}
return OK;
}
int main(){
StaticLinkList L;
Status status;
InitList(L);
printf("初始化后数组长度:%d\n",ListLength(L));
ListInsert(L,1,'a');
ListInsert(L,1,'b');
ListInsert(L,1,'c');
ListInsert(L,1,'d');
ListInsert(L,1,'e');
ListPrint(L);
ListDelete(L,4);
ListPrint(L);
return 0;
}