一. 代码实现
#include<stdio.h>
#include<malloc.h>
#define SIZE 5
typedef struct StaticLinkedNode {
char data;//储存数据。
int next;//根据next的值来判断下一个节点是哪个。
} *NodePtr;
typedef struct StaticLinkedList {
NodePtr nodes;//指向StaticLinkedNode结构体的指针。
int* used;//确认该结构体的状态。
} *ListPtr;
ListPtr initLinkedList() {
ListPtr tempPtr = (ListPtr)malloc(sizeof(struct StaticLinkedList));
tempPtr->nodes = (NodePtr)malloc(sizeof(struct StaticLinkedNode) * SIZE);
tempPtr->used = (int*)malloc(sizeof(int) * SIZE);
//给tempPtr分配空间。
tempPtr->nodes[0].data = '\0';
tempPtr->nodes[0].next = -1;
tempPtr->used[0] = 1;
for (int i = 1; i < SIZE; i++) {
tempPtr->used[i] = 0;
}
//初始化。
return tempPtr;
}
void printList(ListPtr paraListPtr) {
int p = 0;
//根据next的值来决定遍历。
while (p != -1) {
printf("%c", paraListPtr->nodes[p].data);
p = paraListPtr->nodes[p].next;
}
printf("\n");
}
//进行输出
void insertElement(ListPtr paraListPtr, char paraChar, int paraPosition) {
int p, q, i;
p = 0;
for (i = 0; i < paraPosition; i++) {
//遍历到插入位置
p = paraListPtr->nodes[p].next;
if (p == -1) {
printf("The Position %d is beyond the scope of the list.\n", paraPosition);
return;
}
//判断插入的位置是否超过链表范围。
}
for (i = 1; i < SIZE; i++) {
if (paraListPtr->used[i] == 0) { //找出可用节点。
printf("Space at %d allocated.\n", i);
paraListPtr->used[i] = 1;//使用了该节点。
q = i;
break;
}
}
if (i == SIZE) {
printf("No space.\n");
return;
}
//判断是否有位置。
paraListPtr->nodes[q].data = paraChar;
printf("linking\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\n", paraChar);
return;
}
q = paraListPtr->nodes[p].next;
paraListPtr->nodes[p].next = paraListPtr->nodes[paraListPtr->nodes[p].next].next;
paraListPtr->used[q] = 0;
}
void appendInsertDeleteTest() {
ListPtr tempList = initLinkedList();
printList(tempList);
insertElement(tempList, 'H', 0);
insertElement(tempList, 'e', 1);
insertElement(tempList, 'l', 2);
insertElement(tempList, 'l', 3);
insertElement(tempList, 'o', 4);
printList(tempList);
printf("Deleting 'e'.\n");
deleteElement(tempList, 'e');
printf("Deleting 'a'.\n");
deleteElement(tempList, 'a');
printf("Deleting 'o'.\n");
deleteElement(tempList, 'o');
printList(tempList);
insertElement(tempList, 'x', 1);
printList(tempList);
}
int main() {
appendInsertDeleteTest();
return 0;
}
二. 运行结果
三. 实现方法
静态链表是用一个大的空间存储一个链表的方法,这些数据在逻辑上是连续的,虽然在物理内存中也是连续存储,但是这些数据在物理内存中存储的逻辑与数据之间的逻辑不同。也就是说将一个链表压缩至一个整空间,每个节点紧凑排列,本质上还是一个链表。
要注意的是静态链表中的节点是按照数组来存储的,next是存储的数组的下标,而一个节点对应的used是来表明这个节点是否可以使用。
这种存储方式不能用来存储大量的数据,但对于少量数据来说内存利用率高,可以很快的找到数据,插入删除的速度很快,但是查找的效率低。