题目: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