反转链表需要三个指针,一个保留前一个结点的指针,一个后移指针,一个当前指针。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* curr = head;
while (curr != NULL) {
struct ListNode* nextTemp = curr->next;
curr->next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
// 打印单链表
void printList(struct ListNode* head) {
struct ListNode* curr = head;
while (curr != NULL) {
printf("%d ", curr->val);
curr = curr->next;
}
printf("\n");
}
int main() {
// 创建示例链表 1->2->3
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* second = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* third = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = 1;
head->next = second;
second->val = 2;
second->next = third;
third->val = 3;
third->next = NULL;
printf("原始链表:");
printList(head);
// 反转链表
struct ListNode* reversedHead = reverseList(head);
printf("反转后链表:");
printList(reversedHead);
// 释放内存
free(head);
free(second);
free(third);
return 0;
}
画图讲解链表反转的过程,在反转链表的实现过程中一开始是这样的:
当curr不为空的时候,也就是不是最后一个结点时开始执行反转:
此时的prev就是反转链表后的头结点,链表反转完毕。