題目描述
輸入一個鏈表,反轉鏈表後,輸出鏈表的所有元素。
/*
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 nullptr;
ListNode *pNewlist = nullptr;
ListNode *pCur = pHead;
ListNode *pPre = nullptr;
while(pCur!=nullptr)
{
ListNode *pNext = pCur->next;
if(pNext == nullptr) //注意當下一個節點爲空時,要保存當前結點
pNewlist = pCur;
pCur->next = pPre;
pPre = pCur;
pCur = pNext;
}
return pNewlist;
}
};