C语言单向链表反转算法详解及代码实现
可以通过迭代的方式实现单向链表的反转。具体步骤如下:\n\n1. 定义一个指针变量prev,用于保存当前节点的前一个节点,初始值为NULL。\n2. 定义一个指针变量current,用于保存当前节点,初始值为链表的头节点。\n3. 定义一个指针变量next,用于保存当前节点的下一个节点。\n4. 循环遍历链表,直到当前节点为NULL,每次迭代执行以下操作:\n 1. 将next指向当前节点的下一个节点。\n 2. 将当前节点的next指针指向prev。\n 3. 更新prev为当前节点。\n 4. 更新current为next。\n5. 最后将链表的头节点指向prev,完成反转。\n\n以下为具体实现代码:\n\nc\n#include <stdio.h>\n#include <stdlib.h>\n\n// 定义链表节点结构体\ntypedef struct Node {\n int data;\n struct Node* next;\n} Node;\n\n// 创建链表节点\nNode* createNode(int data) {\n Node* newNode = (Node*)malloc(sizeof(Node));\n newNode->data = data;\n newNode->next = NULL;\n return newNode;\n}\n\n// 反转链表\nNode* reverseList(Node* head) {\n Node* prev = NULL;\n Node* current = head;\n Node* next = NULL;\n\n while (current != NULL) {\n next = current->next;\n current->next = prev;\n prev = current;\n current = next;\n }\n\n return prev;\n}\n\n// 打印链表\nvoid printList(Node* head) {\n Node* current = head;\n while (current != NULL) {\n printf("%d ", current->data);\n current = current->next;\n }\n printf("\n");\n}\n\nint main() {\n // 创建链表:1->2->3->4->5\n Node* head = createNode(1);\n head->next = createNode(2);\n head->next->next = createNode(3);\n head->next->next->next = createNode(4);\n head->next->next->next->next = createNode(5);\n\n printf("原链表:");\n printList(head);\n\n // 反转链表\n head = reverseList(head);\n\n printf("反转后的链表:");\n printList(head);\n\n return 0;\n}\n\n\n运行结果为:\n\n\n原链表:1 2 3 4 5 \n反转后的链表:5 4 3 2 1 \n
原文地址: https://www.cveoy.top/t/topic/qzut 著作权归作者所有。请勿转载和采集!