给我一个能输出值的单链表的c语言代码
时间: 2023-05-31 16:07:09 浏览: 48
这是一个能输出值的单链表的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结点
struct Node {
int data; // 数据
struct Node* next; // 指向下一结点
};
// 打印链表中每个结点的数值
void printList(struct Node* head) {
struct Node* current = head; // 定义当前结点为头结点
while (current != NULL) { // 遍历链表
printf("%d ", current->data);// 输出当前结点的数值
current = current->next; // 将当前结点指向下一结点
}
printf("\n"); // 输出一个换行符
}
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; // 头结点储存1
head->next = second; // 头结点指向第二结点
second->data = 2; // 第二结点储存2
second->next = third; // 第二结点指向第三结点
third->data = 3; // 第三结点储存3
third->next = NULL; // 第三结点指向NULL
// 输出链表
printList(head);
// 释放内存
free(head);
free(second);
free(third);
return 0;
}
```