輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode*pnode=pHead;
ListNode*ppre=NULL;//前一個節點
ListNode*pnewhead=NULL;//翻轉之後的新頭結點
if(pHead==NULL)//空鏈表,(注意魯棒性)
return NULL;
while(pnode!=NULL){
ListNode*ptemp=pnode->next;//記住將要斷開的鏈表節點,以方便後面的翻轉。
if(ptemp==NULL)
pnewhead=pnode;
pnode->next=ppre;
ppre=pnode;
pnode=ptemp;
}
return pnewhead;
}
};