2025年c++单向链表反转(反转单向链表c语言)

c++单向链表反转(反转单向链表c语言)以下是 C 语言 中将新节点添加到链表 尾部的示例代码 include lt stdio h gt include lt stdlib h gt 定义 em 链表 em 结构体 struct Node int data struct Node next 在 em 链表 lt em

大家好,我是讯享网,很高兴认识大家。

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


讯享网

#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; // 定义<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-&gt;data = new_data; new_node-&gt;next = NULL; // 如果<em>链表</em>为空,则将新节点设置为头节点 if (*head_ref == NULL) { *head_ref = new_node; return; } // 遍历<em>链表</em>,找到最后一个节点 while (last-&gt;next != NULL) { last = last-&gt;next; } // 将新节点添加到<em>链表</em>尾部 last-&gt;next = new_node; return; } // 测试代码 int main() { struct Node* head = NULL; // 初始化<em>链表</em>为空 // 添加节点 append(&amp;head, 1); append(&amp;head, 2); append(&amp;head, 3); // 遍历<em>链表</em>并输出每个节点的值 struct Node* current = head; while (current != NULL) { printf(&quot;%d &quot;, current-&gt;data); current = current-&gt;next; } return 0; } 

讯享网
小讯
上一篇 2025-05-26 07:14
下一篇 2025-06-12 09:24

相关推荐

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