反转链表其实不难
我在刚拿到这道题的时候以为要三个指针,其实不然,只需要两个指针即可,另一个为临时指针存储cur的下一个节点
第一次的错误代码分析
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//传统双指针
ListNode *temp;
ListNode *pre=nullptr;
ListNode *cur = head;
while(cur->next){
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
head = cur;
return head;
}
};
首先呢,while的循环条件写错了,因为我们要反转的是整个链表,如果只执行到cur->next会导致最后一个节点没有处理。
其次再分析一下,如果此时的while循环条件改成while(cur)会导致最后的pre其实是最后一节点,最后一次循环的时候cur=null。此时这个程序应该返回指针pre,正确代码如下:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//传统双指针
ListNode *temp;
ListNode *pre=nullptr;
ListNode *cur = head;
while(cur){
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
想清楚每一步递归,想好递归的终止条件。
其实每步的递归就是将当前的两个节点反转,不断调用就行了。
class Solution {
public:
ListNode *reverse(ListNode *pre,ListNode *cur){
if(!cur) return pre;// 非常神奇,最后一定会执行到cur==null,此时的pre刚好是链表头
ListNode *temp = cur->next;
cur->next = pre;
//其实就是
//pre = cur;
//cur = temp;
return reverse(cur,temp);
//非常神奇
}
ListNode* reverseList(ListNode* head) {
return reverse(nullptr,head);
}
};