題目描述
輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
題目分析
鏈表的轉置是一個很常見、很基礎的數據結構題了,非遞歸的算法很簡單,用三個臨時指針 pre、head、next 在鏈表上循環一遍即可。遞歸算法也是比較簡單的,但是如果思路不清晰估計一時半會兒也寫不出來吧。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL || pHead->next == NULL)
return pHead;
ListNode* pPre= NULL;
ListNode* pNext = NULL;
while(pHead != NULL)
{
pNext = pHead -> next; //暫存
pHead -> next = pPre;
pPre = pHead;
pHead = pNext;
}
return pPre;
}
};
遞歸實現:
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL || pHead->next == NULL)
return pHead;
ListNode* newHead = ReverseList(pHead -> next);
pHead -> next ->next = pHead;
pHead ->next = NULL;
return newHead;
}
};