题目描述
输入一个链表,反转链表后,输出新链表的表头。
代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *pCur= pHead;
ListNode *pre = NULL; //始终指向反转前pCur的前驱,
ListNode *pNt = NULL; //始终指向反转前pCur的后续
while(pCur!=NULL){
pNt = pCur->next; //防止 pCur->next被破坏,先保存pCur的后续
pCur->next = pre; //反转具体为将前驱变为pCur的后续
pre = pCur; //将pCur变为下一轮的前驱
pCur = pNt; //将pCur的后续变为下一轮的pCur.
}
return pre; //返回pre,而不是pCur,因为最后pNt变为NULL,使得pCur也变为NULL
}
};