要求:如题
思路:
法一:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr||head->next==nullptr)return head;
ListNode *pre=head,*cur=head->next,*tmp;
while(cur->next!=nullptr){
tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
cur->next=pre;
head->next=nullptr;
return cur;
}
};
法二:递归,返回值没啥用,递归只是为了调整headnext后面的分布
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr||head->next==nullptr)return head;
ListNode *headnext=head->next;
ListNode *newhead=reverseList(headnext);
headnext->next=head;
head->next=nullptr;
return newhead;
}
};