https://leetcode-cn.com/problems/reverse-linked-list/
Sol1:迭代:更换替代 or 翻指针
err1:
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* curr = head, *prev = NULL;
while (curr) {
curr->next = prev;
prev = curr;
curr = curr->next;
}
return prev;
}
我们看这句:curr->next = prev;
curr这个结点原本是:curr->next 指向是结点2的地址。
经过这句话后已经变成了指向prev的地址,也就是说丢失了指向结点2的地址。‘
而下面的curr = curr->next;
curr->next指向的是原先prev的地址。
err2:
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* curr = head, *prev = NULL, *next = curr->next;
while (curr) {
curr->next = prev;
prev = curr;
curr = next;
next = next->next;
}
return prev;
}
这个错误在于,当curr为空指针时时,next = next->next为空了,这边错误了。
err2.1
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* curr = head, *prev = NULL, *next = curr->next;
while (curr) {
curr->next = prev;
prev = curr;
curr = next;
if (next) {
next = next->next;
}
}
return prev;
}
next只要不为空指针,就做。
next为空指针的时候,curr也为空了。
可是这个还有错误,当为空链表时,curr为空指针,但是curr->next就又错了。
AC1
struct ListNode* reverseList(struct ListNode* head){
if (head == NULL) {
return NULL;
}
struct ListNode* curr = head, *prev = NULL, *next = curr->next;
while (curr) {
curr->next = prev;
prev = curr;
curr = next;
if (next) {
next = next->next;
}
}
return prev;
}
提前判断,如果是空链表则返回为空。
总的来说,就是两个错误
1.next->next变成了NULL->next
2.head == NULL的时候
于是有了AC2
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* curr = head, *prev = NULL;
while (curr) {
struct ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
首先看1的解决,
一个是上来就先走了一步,然后再跟着移,所以差一步再后报错。
一个是在循环中走,少走了一步,所以会和curr同步,不会报错。
2.当head为NULL时,在做while循环时,curr为NULL不做,返回prev是NULL,成功。
时间复杂度:O(n),n为链表的长度。需要遍历(遍:一个动作从开始到结束的过程),(历:经过)链表一次。
空间复杂度:O(1)