用C语言写一段单链表尾插法
时间: 2023-12-29 17:47:41 浏览: 81
下面是一段使用单链表尾插法的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 尾插法插入节点
void insert_node(struct Node** head_ref, int new_data) {
// 创建新节点
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
// 如果链表为空,将新节点设为头节点
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
// 找到最后一个节点
struct Node* last = *head_ref;
while (last->next != NULL) {
last = last->next;
}
// 将新节点插入到链表末尾
last->next = new_node;
}
// 打印链表
void print_list(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
// 创建头节点
struct Node* head = NULL;
// 插入节点
insert_node(&head, 1);
insert_node(&head, 2);
insert_node(&head, 3);
// 打印链表
print_list(head);
return 0;
}
```
这段代码定义了一个 `Node` 结构体来表示链表节点,其中包含一个整数 `data` 和一个指向下一个节点的指针 `next`。`insert_node` 函数用于在链表末尾插入新节点,它首先创建一个新节点,然后找到链表的最后一个节点,将新节点插入到链表末尾。`print_list` 函数用于遍历链表,并打印每个节点的 `data` 值。在 `main` 函数中,我们创建了一个头节点,并插入了三个新节点,然后打印整个链表。
阅读全文
相关推荐
















