方法:遍历
cpp
/**
* 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) {
ListNode* A=nullptr;
ListNode* B=nullptr;
while(head!=nullptr){
B=head;
head=head->next;
B->next=A;
A=B;
}
head=B;
return head;
}
};
方法:递归
cpp
/**
* 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* recurveReverseList(ListNode* A,ListNode* B){
if(B->next==nullptr){
B->next=A;
return B;
}
ListNode* T=B;
B=B->next;
T->next=A;
A=T;
return recurveReverseList(A,B);
}
ListNode* reverseList(ListNode* head) {
if(head==nullptr){
return head;
}
return recurveReverseList(nullptr,head);
}
};