题目:输入一个链表,反转链表后,输出新链表的表头。
注意对异常输入进行判定。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
//定义前后两个指针p1, p2
//相当于在链表的头部插入新的节点
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr) return nullptr;
ListNode* pPre =pHead; //指向翻转后链表的头节点
ListNode* pCurrent = pHead->next;
while(pCurrent!=nullptr){
ListNode *pNext = pCurrent->next;
pCurrent->next = pPre;
pPre = pCurrent;
pCurrent = pNext;
}
pHead->next = nullptr; //链表的最后应该是一个空指针
return pPre;
}
};