题目链接:206.反转链表
注意
循环条件和指针的移动顺序是比较容易出错的,正确编写代码的要点在于反复严格的按照代码手动模拟解题过程。这样能够找出代码中的逻辑漏洞。
代码
/**
* 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 nullptr;
ListNode * pre = head;
ListNode * cur = pre->next;
ListNode * next = cur;
pre->next = nullptr;
while (cur) {
next = next->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};