以下是
C语言中将新节点添加到
链表尾部的示例代码:
到此这篇c++单向链表反转(反转单向链表c语言)的文章就介绍到这了,更多相关内容请继续浏览下面的相关 推荐文章,希望大家都能在编程的领域有一番成就!#include <stdio.h>
#include <stdlib.h>
// 定义
链表结构体
struct Node {
int data;
struct Node* next;
};
// 在
链表尾部添加新节点
void append(struct Node head_ref, int new_data) {
// 为新节点分配内存
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; // 用于遍历
链表// 设置新节点的值和下一个节点为NULL
new_node->data = new_data;
new_node->next = NULL;
// 如果
链表为空,则将新节点设置为头节点
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
// 遍历
链表,找到最后一个节点
while (last->next != NULL) {
last = last->next;
}
// 将新节点添加到
链表尾部
last->next = new_node;
return;
}
// 测试代码
int main() {
struct Node* head = NULL; // 初始化
链表为空
// 添加节点
append(&head, 1);
append(&head, 2);
append(&head, 3);
// 遍历
链表并输出每个节点的值
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
return 0;
}
版权声明:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权、违法违规、事实不符,请将相关资料发送至xkadmin@xkablog.com进行投诉反馈,一经查实,立即处理!
转载请注明出处,原文链接:https://www.xkablog.com/cjjbc/20917.html