面试手撕代码——链表反转(递归、迭代)
递归
class Solution {
public:
ListNode* ReverseList(ListNode* head) {
if(!head||!head->next) return head;
ListNode* ans = ReverseList(head->next);
head->next->next = head;
head->next = NULL;
return ans;
}
};
迭代
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(!pHead) return NULL;
ListNode* pre = NULL,*cur = pHead,*nex = NULL;
while(cur){
nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
return pre;
}
};