一.题目解析

算法解析:1.循环
三指针法:prev,cur,next,然后cur指针指向prev实现反转,注意指针前进的顺序
代码实现
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* prev=nullptr;
ListNode* cur=head;
while(cur!=nullptr)
{
ListNode* next=cur->next;
cur->next=prev;
prev=cur;
cur=next;
}
return prev;
}
};
算法解析2:递归
思路1:

思路2:

递归代码实现
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) {
if(head==nullptr||head->next==nullptr)return head;//边界情况
ListNode*newhead= reverseList(head->next);//深度优先遍历
head->next->next=head;
head->next=nullptr;
return newhead;
}
};