題目:Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
連接:Merge Two Sorted Lists
解法:比較兩鏈表頭值大小,將小者插入新鏈表尾,若任一鏈表爲空,直接將另一鏈表插入新鏈表尾。時間O(m+n)
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *head = new ListNode(0);
head->next = NULL;
ListNode *p = head;
while (l1 || l2) {
ListNode *tmp = new ListNode(0);
tmp->next = NULL;
if (!l1 && l2) {
tmp->val = l2->val;
l2 = l2->next;
} else if (!l2 && l1) {
tmp->val = l1->val;
l1 = l1->next;
} else if (l1->val > l2->val) {
tmp->val = l2->val;
l2 = l2->next;
} else {
tmp->val = l1->val;
l1 = l1->next;
}
p->next = tmp;
p = p->next;
}
p = head;
head = head->next;
p->next = NULL;
delete(p);
return head;
}
};
Runtime: 9 ms