什么是静态链表,代码展示
时间: 2024-04-21 21:23:05 浏览: 15
静态链表是一种使用数组实现的链表数据结构。下面是一个简单的静态链表的代码示例:
```c
#include <stdio.h>
#define MAX_SIZE 100
// 定义静态链表的节点结构
typedef struct {
int data;
int next; // 游标,表示下一个节点在数组中的索引
} Node;
// 初始化静态链表
void initStaticList(Node list[]) {
for (int i = 0; i < MAX_SIZE - 1; i++) {
list[i].next = i + 1; // 设置游标,使得每个节点都指向下一个节点
}
list[MAX_SIZE - 1].next = -1; // 设置最后一个节点的游标为-1,表示链表结束
}
// 插入节点
void insertNode(Node list[], int data) {
int newNodeIndex = list[0].next; // 获取第一个可用节点的索引
if (newNodeIndex != -1) {
list[0].next = list[newNodeIndex].next; // 更新第一个可用节点的索引
list[newNodeIndex].data = data;
list[newNodeIndex].next = -1;
printf("插入节点:%d\n", data);
} else {
printf("静态链表已满,无法插入节点:%d\n", data);
}
}
// 打印静态链表
void printStaticList(Node list[]) {
int currentIndex = list[0].next; // 获取第一个节点的索引
printf("静态链表内容:");
while (currentIndex != -1) {
printf("%d ", list[currentIndex].data);
currentIndex = list[currentIndex].next; // 更新当前节点的索引
}
printf("\n");
}
int main() {
Node staticList[MAX_SIZE];
initStaticList(staticList);
insertNode(staticList, 1);
insertNode(staticList, 2);
insertNode(staticList, 3);
printStaticList(staticList);
return 0;
}
```
在上述示例中,我们使用一个静态数组 `staticList` 来实现静态链表。通过初始化函数 `initStaticList`,我们将数组中的每个元素设置为可用节点,并通过游标将它们连接起来。
插入节点的函数 `insertNode` 首先从第一个可用节点中获取一个节点,然后更新第一个可用节点的索引。接着,我们将节点的数据域设置为给定的数据,并将游标设置为-1,表示链表结束。
最后,通过函数 `printStaticList`,我们遍历静态链表并打印出其中的数据。在主函数中,我们示范了插入节点和打印链表的操作。