
迭代版本
点击查看代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
auto a = head, b = a->next;
while (b) {
auto c = b->next;
b->next = a;
a = b, b = c;
}
head->next = NULL;
return a;
}
};
- 当是空链表或只有一个结点时,直接返回头结点 head;
- 当 b 不为空时,a 指向当前结点 p,b 指向 p->next,c 指向 p->next->next,每次将 b->next = a,并移动指针 a = b, b = c;
- head 此时指向的是新链表的尾结点,head->next = NULL;
- 新链表的头结点是 a;
递归版本
点击查看代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
auto tail = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return tail;
}
};
- 当是空链表或只有一个结点时,直接返回头结点 head;
- 递归调用 reverseList(head->next),最后一次递归,反转链表尾结点为 head->next,head->next->next = NULL,此时执行 head->next->next = head 对 head 结点进行反转,head 变为新的反转链表的尾结点,head->next = NULL;
- 返回的 tail 是反转链表的头结点;