題目描述
輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。
遞歸(也可以使用非遞歸的方法):
另:合併k個有序鏈表採用的是堆的辦法
/*
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 && !pHead2)
return NULL;
if(!pHead1)
return pHead2;
if(!pHead2)
return pHead1;
if(pHead1 ->val < pHead2 ->val)
{
pHead1 ->next = Merge(pHead1 ->next, pHead2);
return pHead1;
}
else
{
pHead2 ->next = Merge(pHead1, pHead2 ->next);
return pHead2;
}
}
};