思路定义一个节点之前头结点前面,一个指向头结点,一个临时节点用于cur节点的下步循环
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode*prev=nullptr;
ListNode*temp=nullptr;
ListNode*cur=head;
while(cur!=nullptr){
temp=cur->next;
cur->next=prev;
prev=cur;
cur=temp;
}
return prev;
}
};
class Solution {
public:
ListNode* myreverse(ListNode*pre,ListNode*cur){
if(cur==nullptr)return pre;
ListNode*temp=cur->next;
cur->next=pre;
return myreverse(cur,temp);
}
ListNode* reverseList(ListNode* head) {
return myreverse(NULL,head);
}
};
参考lubuladong
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr||head->next==nullptr)return head;
ListNode*last=reverseList(head->next);
head->next->next=head;
head->next=nullptr;
return last;
}
};