使用c语言写一个构建链表的代码
时间: 2023-05-18 22:07:20 浏览: 111
以下是使用 C 语言构建链表的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* n) {
while (n != NULL) {
printf("%d ", n->data);
n = n->next;
}
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// 分配 3 个节点
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1; // 设置第一个节点的数据
head->next = second; // 第一个节点指向第二个节点
second->data = 2; // 设置第二个节点的数据
second->next = third; // 第二个节点指向第三个节点
third->data = 3; // 设置第三个节点的数据
third->next = NULL; // 第三个节点指向 NULL,表示链表结束
printList(head); // 输出链表
return 0;
}
```
这段代码可以构建一个包含 3 个节点的链表,每个节点包含一个整数数据和一个指向下一个节点的指针。在 `main` 函数中,我们首先分配 3 个节点的内存空间,然后设置每个节点的数据和指针,最后输出整个链表。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)