- 递归的方法反转整个链表
- 其中,
head->next->next = head
表示已经被逆转好的链表的最后一个元素的下一位,连到当前元素上
- 其中,
递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* last = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return last;
}
};
循环
- 循环方法显然避免了栈调用的过程
- 值得注意的是循环体内部,几个指针移动的顺序。显然code2更优雅许多倍
code1
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr) return NULL;
ListNode* dummy = NULL;
ListNode* pre = dummy;
ListNode* cur = head;
ListNode* post= head->next;
while(cur!=NULL){
cur->next = pre;
pre = cur;
cur = post;
if(post) post=post->next; // 最后一次,post会指向 null->next 此时会报错,因此用循环判断下
}
return pre;
}
};
code2
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* cur = head;
if(cur == NULL)
return NULL;
ListNode* next;
while(cur!=NULL){
next = cur->next; // 先把下一个点存起来
cur->next = pre; // 当前点指向上一个点,反转
pre = cur; // 上一个点的指针移动到当前节点上
cur = next; // 当前节点后移
}
return pre;
}
};