# include <stdio.h>
# include <stdlib.h>
# define DEFAULT_SIZE 5
typedef struct StaticLinkNode {
char data;
int next;
}*NodePtr;
typedef struct StaticLinkList {
NodePtr nodes;
int* used;
}*ListPtr;
// 初始化一个带头结点的空静态链表
ListPtr initLinklist() {
ListPtr tempPtr =new StaticLinkList ;
tempPtr->nodes = new StaticLinkNode [DEFAULT_SIZE];
tempPtr->used =new int [DEFAULT_SIZE];
tempPtr->nodes[0].data = '\0'; // 数组的第零个位置存放头结点
tempPtr->nodes[0].next = -1;
tempPtr->used[0] = 1;
for (int i = 1; i < DEFAULT_SIZE; i++) { // 将除了第一个位置的used全部赋值为0,代表空间未被使用
tempPtr->used[i] = 0;
}
return tempPtr;
}
// 输出函数
void printList(ListPtr paraListPtr) {
int p = 0;
p = paraListPtr->nodes[p].next;
if (p == -1) {
printf("The list is empty.\n"); // 当静态链表为空链表时,输出The list is empty
return;
}
else{
while (p != -1) {
printf("%c", paraListPtr->nodes[p].data);
p = paraListPtr->nodes[p].next;
}
}
printf("\r\n");
}
// 插入函数
void insertElement(ListPtr paraListPtr, char element, int position) {
int p, q;
int i;
if (position<1 || position>DEFAULT_SIZE) { // 判断插入位置是否正确,不正确则输出 Position is error!
printf("Position is error!");
return;
}
// step1. 查找插入位置
p = 0;
for (i = 0; i < position; i++) {
p = paraListPtr->nodes[p].next;
if (p == -1) {
printf("The position %d is beyond the scope of the list.\r\n", position);
return;
}
}
//step2. 创建一个新节点
for (i = 1; i < DEFAULT_SIZE; i++) {
if (paraListPtr->used[i] == 0) {
printf("Space at %d allocated.\r\n", i);
paraListPtr->used[i] = 1;
q = i;
break;
}
}
if (i == DEFAULT_SIZE) {
printf("No space.\r\n");
return;
}
paraListPtr->nodes[q].data = element;
//step3.进行连接
printf("linking\r\n");
paraListPtr->nodes[q].next = paraListPtr->nodes[p].next;
paraListPtr->nodes[p].next = q;
}
// 删除函数
void deleteElement(ListPtr paraListPtr, char paraChar) {
int p, q;
p = 0;
while (paraListPtr->nodes[p].next != -1 && paraListPtr->nodes[paraListPtr->nodes[p].next].data != paraChar) {
p = paraListPtr->nodes[p].next;
}
if (paraListPtr->nodes[p].next == -1) {
printf("Cannot delete %c\r\n", paraChar);
return;
}
q = paraListPtr->nodes[p].next;
paraListPtr->nodes[p].next = paraListPtr->nodes[paraListPtr->nodes[p].next].next;
paraListPtr->used[q] = 0;
}
void InsertDeleteTest() {
//step1. 创建空链表
ListPtr tempList = initLinklist();
printList(tempList);
//step2. 添加字母
insertElement(tempList, 'H', 0);
insertElement(tempList, 'e', 1);
insertElement(tempList, 'l', 2);
insertElement(tempList, 'l', 3);
insertElement(tempList, 'o', 4);
printList(tempList);
//step3. 删除字母
printf("Deleting 'e'.\r\n");
deleteElement(tempList, 'e');
printf("Deleting 'a'.\r\n");
deleteElement(tempList, 'a');
printf("Deleting 'o'.\r\n");
deleteElement(tempList, 'o');
printList(tempList);
insertElement(tempList, 'x', 1);
printList(tempList);
}
int main() {
InsertDeleteTest();
return 0;
}
静态链表就是用数组来描述链表,申请两个数组,相当于在计算机中申请了两片空间,DEFAULT_SIZE代表我们申请空间的大小,在这片空间内我们可以自由安排。一个 nodes数组中含有两个参数,一个data用来存放数据,另一个next相当于链表中的指针,通过它可以找到下一个元素的位置。另一个used数组代表空间是否被使用,如果空间被使用则赋值为1,否则赋值为0。
静态链表在插入和删除时,只需要改变下标,不需要移动元素;但是在处理数据长度不确定的问题时,难以解决。