静态链表碰到的情况较少,操作系统文件分配表FAT有用到
#include<iostream>
using namespace std;
const int MaxSize = 10;//确定静态链表的长度
typedef struct Node {
int data;//数据域
int index;//游标
}staticList[MaxSize];
bool initList(staticList);//初始化静态链表,实际内存空间是数组分配模式,程序调用结束之后,空间自动释放
bool createList(staticList, int&);//使用静态链表
bool showList(staticList, int);//打印链表
int main()
{
staticList list;
int temp;
initList(list);
initList(list);
createList(list, temp);
showList(list, temp);
return 0;
}
bool showList(staticList list, int temp) {
if (list == NULL)
return false;
int i = 0;
while (temp != -9999) {
printf("游标为%d的数据元素为:%d\n", temp, list[temp].data);
temp = list[temp].index;
}
return true;
}
bool createList(staticList list, int& temp) {
if (list == NULL)
return false;
int data, initIndex, index;
printf("输入静态链表的游标:");
scanf_s("%d",&initIndex);
temp = initIndex;
int i = 0;
while (initIndex !=-1&&i++<MaxSize) {
if (initIndex < MaxSize || initIndex>0) {
printf("游标位置不对");
return false;
}
printf("输入结点的数据:");
scanf_s("%d", &data);
list[initIndex].data = data;
printf("输入静态链表下一个节点的游标:");
scanf_s("%d", &index);
list[initIndex].index = index;
initIndex = index;
}
return true;
}
bool initList(staticList list) {
if (list == NULL)
return false;
for (int i = 1; i < MaxSize; i++) {
list[i].data = 0;
list[i].index = -9999;
}
return true;
}