题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==nullptr)
return pHead;
ListNode * left=nullptr;
ListNode * cur = pHead;
ListNode * right =pHead->next;
//while right ==null,stop
//if not,process cur ->left,
//move left, cur,right,
while(right!=nullptr){
cur->next=left;
left=cur;
cur=right;
right=right->next;
}
cur->next=left; //the last node
return cur;
}
};
1.便利结束后,还剩末端没弯转
2.过早翻转会丢失后续的node,因此应该提前记下下一个node

