剑指offer24. 反转链表
双指针方式
8ms,8MB
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode * p = head;
if(head&&head->next){
ListNode *q = head->next;
ListNode *r;
head->next = NULL;
while(q){
r = q->next;
q->next = p;
p = q;
q = r;
}
}
return p;
}
};
标答 4ms,7.9MB
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *cur = head,*pre = nullptr;
while (cur != nullptr)
{
ListNode *temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
回顾
- 避免head、head->next同时出现,因为head有可能为NULL,head->next不存在
- 学会设置NULL指针,确保不存在NULL->next的情况。