好的,下面是一个使用 C 语言编写的单向线性链表程序的示例:
``` #include <stdio.h> #include <stdlib.h> #include <string.h>
// 定义结构体表示线性链表的节点 typedef struct node { char data[20]; // 存储字符型数据 struct node *next; // 指向下一个节点的指针 } Node;
// 创建一个空的线性链表 Node* createList() { return NULL; }
// 在线性链表的末尾添加一个新节点 void addNode(Node **list, char *data) { Node newNode = (Node)malloc(sizeof(Node)); // 分配新节点的内存 strcpy(newNode->data, data); // 将数据存储到新节点中 newNode->next = NULL; // 新节点的 next 指针设为 NULL
// 如果线性链表为空,则将新节点设为第一个节点
if (*list == NULL) {
*list = newNode;
}
else {
// 否则,遍历线性链表,找到最后一个节点
Node *current = *list;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode; // 将新节点添加到最后一个节点之后
}
}
// 在线性链表的开头添加一个新节点 void addNodeToBeginning(Node **list, char *data) { Node newNode = (Node)malloc(sizeof(Node)); // 分配新节点的内存 strcpy(newNode->data, data); // 将数据存储到新节点中 newNode->next = *list; // 将新节点的 next 指针设