/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* ReverseList(ListNode* head)
{
ListNode* newhead=nullptr;
ListNode* p=head;
while(p)
{
ListNode* q=p->next;
p->next=newhead;
newhead=p;
p=q;
}
return newhead;
}
};
实际上通过头插法就可以轻松实现了,将头节点之后的节点重新通过头插法的方式插入到头节点的后面,就可以达到逆序的效果了。

京公网安备 11010502036488号