c语言实现简单链表存储
时间: 2023-10-03 18:05:56 浏览: 47
以下是一个简单的链表存储的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表末尾插入新节点
void insert(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
// 打印链表
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
printList(head); // 输出:1 2 3
return 0;
}
```
在上述代码中,我们使用了一个结构体 `Node` 来表示链表中的每个节点,其中包含一个整型数据 `data` 和一个指向下一个节点的指针 `next`。
我们使用 `createNode` 函数来创建一个新节点,并使用 `insert` 函数将其插入到链表的末尾。最后,我们使用 `printList` 函数打印链表中的所有节点的数据。
在主函数中,我们首先将 `head` 指针初始化为 `NULL`,然后调用 `insert` 函数三次来插入三个节点,最后调用 `printList` 函数打印链表中的所有节点的数据。