將兩個排序鏈表合併爲一個新的排序鏈表
給出 1->3->8->11->15->null
,2->null
,
返回 1->2->3->8->11->15->null
。
其中鏈表定義如下:
class ListNode {
public:
int val;
ListNode *next;
ListNode(int val) {
this->val = val;
this->next = NULL;
}
};
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// write your code here
}
};
實際上這一道非常簡單的題目,不過如果不適用遞歸的話,可能會比較繁瑣,所以這裏使用遞歸的方法求解。
首先分析題目,假定有兩個鏈表頭指針 l1,l2;
比較l1->val和l2->val,假定l1較大取出l1->val放到已排好的鏈表中。繼續比較l1->next和l2;
可以看到此時已經存在遞歸調用的mergeLists(l1->next,l2).
那麼遞歸結束的條件是什麼?
就是l1,l2爲空,此時返回另外一個即可。
代碼如下
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(NULL == l1)
return l2;
if(NULL == l2)
return l1;
ListNode* New = NULL;
if(l1->val < l2->val)
{
New = l1;
New->next = mergeTwoLists(l1->next, l2);
}
else
{
New = l2;
New->next = mergeTwoLists(l1, l2->next);
}
return New;
}
};