题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
- 三指针pre、cur、rear
- 头和尾要单独考虑:头节点指向nullptr,尾节点指向pre
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(!pHead) return nullptr;
if(!pHead->next) return pHead;
ListNode* pre = pHead;
ListNode* cur = pHead->next;
ListNode* rear;
pHead->next = nullptr;//头节点指向nullptr
while(cur->next){
rear = cur->next;
cur->next = pre;
pre = cur;
cur = rear;
}
cur->next = pre;//尾节点最后再指向pre
return cur;
}
};