一、題目分析
這是一個遞歸的過程,每次都是鏈表剩餘部分的第一個結點相比較,小的那個就放到新鏈表中;
思考:如果題目改成把可以將3整除的結點放到前邊呢?只需要把判斷條件寫成一個功能函數就可以了
二、代碼分析
注意如果不對輸入的空鏈表參數加以判斷,會造成程序奔潰
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if( pHead1 == NULL)
{
return pHead2;
}
if( pHead2 == NULL)
{
return pHead1;
}
ListNode *newNode = NULL;
if( pHead1->val > pHead2->val)//如果pHead2的值更小
{
newNode = pHead2;
pHead2 = pHead2->next;
newNode->next = Merge(pHead1, pHead2);
}else//如果pHead2的值更小
{
newNode = pHead1;
pHead1 = pHead1->next;
newNode->next = Merge(pHead1, pHead2);
}
return newNode;
}
};