以下是C语言中将新节点添加到链表尾部的示例代码:

#include <stdio.h> #include <stdlib.h> // 定义<em>链表</em>结构体 struct Node { int data; struct Node* next; }; // 在<em>链表</em>尾部添加新节点 void append(struct Node head_ref, int new_data) { // 为新节点分配内存 struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); struct Node* last = *head_ref; // 用于遍历<em>链表</em> // 设置新节点的值和下一个节点为NULL new_node->data = new_data; new_node->next = NULL; // 如果<em>链表</em>为空,则将新节点设置为头节点 if (*head_ref == NULL) { *head_ref = new_node; return; } // 遍历<em>链表</em>,找到最后一个节点 while (last->next != NULL) { last = last->next; } // 将新节点添加到<em>链表</em>尾部 last->next = new_node; return; } // 测试代码 int main() { struct Node* head = NULL; // 初始化<em>链表</em>为空 // 添加节点 append(&head, 1); append(&head, 2); append(&head, 3); // 遍历<em>链表</em>并输出每个节点的值 struct Node* current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } return 0; }
讯享网

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/167206.html