C语言中如何创建节点链表
时间: 2024-05-15 10:12:55 浏览: 10
在 C 语言中,我们可以使用结构体来创建节点链表。下面是一个简单的例子:
```
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
int main() {
// 创建链表节点
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// 分配内存
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;
// 遍历链表并输出
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
// 释放内存
free(head);
free(second);
free(third);
return 0;
}
```
在这个例子中,我们先定义了一个结构体 `Node`,它包含两个成员:一个整型变量 `data` 和一个指向下一个节点的指针 `next`。然后我们分配了三个节点的内存,并将它们链接起来,形成一个简单的链表。最后我们遍历链表,并释放所有节点的内存。