2024年4月30日发(作者:)
c语言单链表尾插法
在C语言中,使用单链表数据结构时,可以使用尾插法来插
入新的节点。尾插法是指在链表的末尾插入新的节点。下面是一
个使用尾插法实现单链表插入节点的示例代码:
c
#include
#include
struct node {
int data;
struct node* next;
};
void insert_at_end(struct node** head, int data) {
// 分配新节点的内存空间
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
// 如果链表为空,将新节点设置为头节点
if (*head == NULL) {
*head = new_node;
return;
}
// 找到链表的末尾节点
struct node* last_node = *head;
while (last_node->next != NULL) {
last_node = last_node->next;
}
// 将新节点插入到链表的末尾
last_node->next = new_node;
}
int main() {
// 创建一个包含3个节点的单链表:1 -> 2 -> 3
struct node* head = NULL;
insert_at_end(&head, 1);
insert_at_end(&head, 2);
insert_at_end(&head, 3);
// 输出链表中的所有节点数据
struct node* current_node = head;
while (current_node != NULL) {
printf("%d ", current_node->data);
current_node = current_node->next;
}
printf("n");
// 释放链表中每个节点的内存空间
current_node = head;
while (current_node != NULL) {
struct node* next_node = current_node->next;
free(current_node);
current_node = next_node;
}
return 0;
}
在这个示例代码中,我们定义了一个结构体node来表示单
链表中的每个节点。每个节点包含一个整数数据data和一个指
向下一个节点的指针next。我们还定义了一个函数
insert_at_end来实现尾插法插入新节点。该函数接受一个指
向头节点的指针和要插入的新节点的数据作为参数。在函数中,
我们首先分配新节点的内存空间,然后将新节点的数据存储在其
中。如果链表为空,将新节点设置为头节点;否则,遍历链表找
到最后一个节点,并将新节点插入到最后一个节点的后面。最后,
我们在main函数中创建一个包含3个节点的单链表,并使用循
环遍历链表输出每个节点的数据。在程序的结尾处,我们释放了
链表中每个节点的内存空间,以避免内存泄漏。
发布者:admin,转转请注明出处:http://www.yc00.com/news/1714417403a2442447.html
评论列表(0条)