在 C 语言中打印链表140
链表是一种线性数据结构,由一组节点组成,每个节点包含一个值和指向下一个节点的指针。在 C 语言中,链表通常使用动态内存分配,节点通过指针连接起来。
输出链表可以帮助调试和可视化数据结构。以下是一个打印链表的 C 语言函数:```c
void print_list(struct node *head)
{
// 检查链表是否为空
if (head == NULL) {
printf("链表为空。");
return;
}
// 遍历链表并打印每个节点的值
struct node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("");
}
```
其中,struct node 是链表节点的结构体,它包含一个 data 字段来存储节点的值,以及一个 next 字段指向下一个节点。
要使用此函数打印链表,您需要:
将该函数添加到您的 C 程序中。
创建链表并将其头节点存储在变量 head 中。
调用 print_list 函数,传入头节点作为参数。
示例:```c
#include
#include
struct node {
int data;
struct node *next;
};
int main()
{
// 创建一个链表
struct node *head = NULL;
// 添加一些节点到链表
struct node *new_node;
new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = 10;
new_node->next = head;
head = new_node;
new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = 20;
new_node->next = head;
head = new_node;
// 打印链表
print_list(head);
return 0;
}
```
输出:```
20 10
```
2025-02-10
上一篇:用 C 语言计算函数的值
下一篇:负数在 C 语言中的输出格式化
Java数组元素:从基础到高级操作的深度解析
https://www.shuihudhg.cn/134539.html
PHP Web应用的安全基石:全面解析数据库SQL注入防御
https://www.shuihudhg.cn/134538.html
Python函数入门到进阶:用简洁代码构建高效程序
https://www.shuihudhg.cn/134537.html
PHP中解析与提取代码注释:DocBlock、反射与AST深度探索
https://www.shuihudhg.cn/134536.html
Python深度解析与高效处理.dat文件:从文本到二进制的实战指南
https://www.shuihudhg.cn/134535.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html