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 语言中通过函数调用数组**

下一篇:利用 C 语言遍历和输出链表