单向链表反转(单向链表反转c语言)

单向链表反转(单向链表反转c语言)大家好 我是贤弟 一 什么是单链表反转 单链表反转是指将单链表中的节点顺序颠倒过来 即原来的尾节点变为头节点 原来的头节点变为尾节点 二 以下是用 C 语言实现单链表反转的代码 c include include p p p 定义单链表节点结构体 typedef struct node int data struct node next p

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



大家好,我是贤弟!

一、什么是单链表反转?

单链表反转是指将单链表中的节点顺序颠倒过来,即原来的尾节点变为头节点,原来的头节点变为尾节点。

二、以下是用C语言实现单链表反转的代码:


讯享网

c#include #include </p><p>/* 定义单链表节点结构体 */typedef struct node { int data; struct node *next;} Node;</p><p>/* 创建单链表 */Node* createList(int n) { Node *head = NULL, *p = NULL, *q = NULL; int i, x; for (i = 1; i &lt;= n; i++) { printf(&quot;请输入第%d个节点的值:&quot;, i); scanf(&quot;%d&quot;, &amp;x); p = (Node*)malloc(sizeof(Node)); p-&gt;data = x; p-&gt;next = NULL; if (head == NULL) { head = p; } else { q-&gt;next = p; } q = p; } return head;}</p><p>/* 反转单链表 */Node* reverseList(Node *head) { Node *p = NULL, *q = NULL, *r = NULL; p = head; while (p != NULL) { r = p-&gt;next; p-&gt;next = q; q = p; p = r; } head = q; return head;}</p><p>/* 输出单链表 */void printList(Node *head) { Node *p = head; while (p != NULL) { printf(&quot;%d &quot;, p-&gt;data); p = p-&gt;next; } printf(&quot; &quot;);}</p><p>int main() { int n; printf(&quot;请输入单链表的长度:&quot;); scanf(&quot;%d&quot;, &amp;n); Node *head = createList(n); printf(&quot;原始单链表:&quot;); printList(head); head = reverseList(head); printf(&quot;反转后的单链表:&quot;); printList(head); return 0;}

注意:

程序中,首先定义了单链表节点结构体,包含数据域和指向下一个节点的指针。

然后通过createList函数创建单链表,其中循环读入每个节点的值,并将其插入链表中。

reverseList函数实现单链表反转,通过三个指针分别指向当前节点、上一个节点和下一个节点,依次将当前节点的指针指向上一个节点,然后将三个指针向后移动一个节点。最后,通过printList函数输出单链表的值。

main函数中,读入单链表长度,创建单链表,输出原始单链表,反转单链表后再次输出。

小讯
上一篇 2025-06-02 14:25
下一篇 2025-06-02 21:24

相关推荐

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