采用迭代方式反转链表
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pReversedHead = NULL;
ListNode* curr = pHead;
ListNode* pPrev = NULL;
while(curr != NULL) {
ListNode* pNext = curr->next;
if(pNext == NULL)
pReversedHead = curr;
curr->next = pPrev;
pPrev = curr;
curr = pNext;
}
return pReversedHead;
}
};
递归
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL) return NULL; //边界条件 空指针
if(pHead->next == NULL) return pHead;
ListNode* pReversedHead = ReverseList(pHead->next);
pHead->next->next = pHead;
pHead->next = NULL;
return pReversedHead;
}
};