如何用c语言完成链表逆置
时间: 2025-03-29 20:03:45 浏览: 28
### C语言实现链表逆置
以下是基于提供的参考资料以及专业知识编写的C语言实现链表逆置的代码示例:
#### 方法一:迭代法
此方法通过三个指针完成链表的逆置操作。`prev` 指向前一个节点,初始化为 `NULL`;`current` 指向当前节点,初始化为链表头节点;`next` 用于临时存储 `current->next` 的值。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct ListNode {
int val;
struct ListNode* next;
};
// 反转链表函数
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* prev = NULL; // 前驱节点
struct ListNode* current = head; // 当前节点
struct ListNode* next = NULL; // 下一节点
while (current != NULL) { // 遍历整个链表
next = current->next; // 保存下一节点
current->next = prev; // 将当前节点的next指向其前驱节点
prev = current; // 移动prev到当前节点位置
current = next; // 移动current到下一节点位置
}
return prev; // 返回新的头节点
}
```
上述代码实现了链表的逆序功能[^1]。
---
#### 方法二:递归法
递归方法的核心思想是从链表尾部开始逐步构建新链表。当到达最后一个节点时,将其作为新链表的头部并逐层返回。
```c
// 使用递归方式反转链表
struct ListNode* reverseListRecursive(struct ListNode* head) {
if (head == NULL || head->next == NULL) { // 如果链表为空或者只有一个节点,则直接返回
return head;
}
struct ListNode* newHead = reverseListRecursive(head->next); // 递归调用直到找到最后的节点
head->next->next = head; // 将当前节点挂载到下一层节点之后
head->next = NULL; // 断开原链表中的连接关系
return newHead; // 返回新的头节点
}
```
这种方法利用了栈的思想来处理链表节点之间的顺序调整[^2]。
---
#### 测试代码
为了验证以上两种方法的有效性,可以编写如下测试程序:
```c
void printList(struct ListNode* node) {
while (node != NULL) {
printf("%d ", node->val);
node = node->next;
}
printf("\n");
}
int main() {
// 创建链表: 1 -> 2 -> 3 -> 4 -> 5
struct ListNode* head = malloc(sizeof(struct ListNode));
struct ListNode* second = malloc(sizeof(struct ListNode));
struct ListNode* third = malloc(sizeof(struct ListNode));
struct ListNode* fourth = malloc(sizeof(struct ListNode));
struct ListNode* fifth = malloc(sizeof(struct ListNode));
head->val = 1;
head->next = second;
second->val = 2;
second->next = third;
third->val = 3;
third->next = fourth;
fourth->val = 4;
fourth->next = fifth;
fifth->val = 5;
fifth->next = NULL;
printf("Original List:\n");
printList(head);
// 调用迭代法反转链表
struct ListNode* reversedHeadIterative = reverseList(head);
printf("Reversed List (Iterative):\n");
printList(reversedHeadIterative);
// 调用递归法反转链表
struct ListNode* reversedHeadRecursive = reverseListRecursive(reversedHeadIterative);
printf("Reversed List (Recursive):\n");
printList(reversedHeadRecursive);
return 0;
}
```
这段代码展示了如何创建链表、打印链表内容,并分别使用迭代和递归的方式对其进行逆置[^3]。
---
###
阅读全文
相关推荐

















