- Problem: merge 兩個已排序的 lists
- Solution:
- 可以直接 iteratively 比較兩個 list 元素, 一個一個 push
- recursive
- 終止條件: list0 或 list1已到結尾, 則 return 另一個 list
- 當前判斷:
- 將最小元素的 next 指向 recursive return 回來的 list
- Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (NULL == l1) return l2;
if (NULL == l2) return l1;
if (l1->val < l2->val)
{
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
沒有留言:
張貼留言