一.题目解析

算法解析:



结合画图和头插代码就很好理解了
二.代码编写:
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=new ListNode(0);
ListNode*cur=head;
while(cur!=nullptr)
{
ListNode*next=cur->next;//注意顺序和位置
cur->next=newhead->next;
newhead->next=cur;
cur=next;
}
cur=newhead->next;
delete newhead;
return cur;
}
};