坑:pHead == null要写在前面,如果pHead->next == null写在前面的话,会导致段错误,因为传入空链表时,访问了空指针的next
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *l,*r;
if(pHead == nullptr || pHead->next == nullptr){
return pHead;
}
l = pHead->next;
r = l->next;
pHead->next = nullptr;
while(l != nullptr){
l->next = pHead;
pHead = l;
l = r;
if(r != nullptr)
r = r->next;
}
return pHead;
}
};