/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <cstddef>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    ListNode* ReverseList(ListNode* head) {
        // write code here
        //健壮性判断
        
        ListNode* pre = nullptr;
        ListNode* next  = nullptr;
        while (head != nullptr) {
            next = head ->next;
            head -> next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
};

关键点:

既要沿着next节点向后遍历,又要改变next的指向,指向前一个节点

解决

所以需要额外的两个指针pre,next,分别记录前一个节点和后一个节点的地址