C 语言链表输出98
链表是一种非连续的线性数据结构,它由一系列称为节点的元素组成。每个节点包含一个数据项和指向下一个节点的指针。链表通常用于存储动态数据,因为它易于插入和删除元素。
在 C 语言中,可以创建链表并输出其内容。以下是如何做到这一点:
创建链表
要创建链表,可以使用以下代码:```c
struct node {
int data;
struct node *next;
};
struct node *head = NULL;
```
这段代码创建了一个名为 head 的链表头。链表头是一个指向链表中第一个节点的指针。由于链表最初为空,因此 head 被初始化为 NULL。
向链表中插入元素
要向链表中插入元素,可以使用以下代码:```c
struct node *insert(struct node *head, int data) {
struct node *new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = head;
return new_node;
}
```
此函数接受链表头和要插入的数据作为参数。它分配一个新节点,将数据分配给该节点,并将新节点链接到链表中。它然后返回更新后的链表头。
输出链表
要输出链表,可以使用以下代码:```c
void print_list(struct node *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
}
```
此函数接受链表头として参数。它遍历链表,输出每个节点的数据。它一直遍历到遇到 NULL 节点(即链表结束)。
示例
以下是一个 C 语言程序的示例,它演示了如何在链表中插入元素并输出链表的内容:```c
#include
#include
struct node {
int data;
struct node *next;
};
struct node *insert(struct node *head, int data) {
struct node *new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = head;
return new_node;
}
void print_list(struct node *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
}
int main() {
struct node *head = NULL;
head = insert(head, 10);
head = insert(head, 20);
head = insert(head, 30);
head = insert(head, 40);
print_list(head);
return 0;
}
```
输出:```
40 30 20 10
```
2024-10-23
下一篇:利用 C 语言遍历和输出链表
Python字符串查找与判断:从基础到高级的全方位指南
https://www.shuihudhg.cn/134118.html
C语言如何高效输出字符串“inc“?深度解析printf、puts及格式化输出
https://www.shuihudhg.cn/134117.html
PHP高效获取CSV文件行数:从小型文件到海量数据的最佳实践与性能优化
https://www.shuihudhg.cn/134116.html
C语言控制台图形输出:从入门到精通的ASCII艺术实践
https://www.shuihudhg.cn/134115.html
Python在Linux环境下的执行与自动化:从基础到高级实践
https://www.shuihudhg.cn/134114.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