写一个遍历链表的C代码
时间: 2024-05-13 22:14:08 浏览: 12
以下是一个遍历链表的C代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 遍历链表并打印每个节点的值
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
// 创建链表
Node *head = NULL;
Node *second = NULL;
Node *third = NULL;
head = (Node*) malloc(sizeof(Node));
second = (Node*) malloc(sizeof(Node));
third = (Node*) malloc(sizeof(Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
// 遍历链表并打印每个节点的值
printList(head);
// 释放链表内存
free(head);
free(second);
free(third);
return 0;
}
```
该代码创建了一个简单的链表,包含三个节点,然后使用 `printList` 函数遍历链表并打印每个节点的值。最后释放链表内存。