题目描述
法一)迭代法
class Solution{
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* cur = head;
while(cur){
ListNode* next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev; //最后一步cur为空,prev为最后一个结点
}
};
法二)递归
class Solution{
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next){ //结点为空或者只有一个结点
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next=NULL;
return newHead;
}
};