/**
* 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) {
// write code here
ListNode* newHead = nullptr;
ListNode* curr = head;
while(curr) {
ListNode* next = curr->next;//创建临时节点,防止断裂
curr->next = newHead;//头插法第一步:源节点的next指向新链表的头结点
newHead = curr;//头插法第二步:然后,将新链表的头节点往前移动、执行刚刚那个源节点
curr = next;//不能用curr = curr->next,因为curr->next已经被头插法的第一步覆盖掉了
}
return newHead;
}
};