/**
* 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* pre = nullptr;
ListNode* p = head;
while (p != NULL) {
ListNode* t = p->next;
//指针值的转换也有先后顺序讲究,这里的t=pnext不能放在p=t之后,否则会导致越界,
//反之,当你发现p的后继t可能越界时,通过调整代码执行的顺序,便能化险为夷
p->next = pre;
pre = p;
p = t;
}
return pre;
}
};