Problem:
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
思路:
按照归并排序的思路,归并为一个链表,然后将归并完剩下的链表链接到归并的链表上。
Solution (C++):
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
typedef ListNode* L;
if (!l1) return l2;
if (!l2) return l1;
ListNode l(0);
L l3 = &l, p = &l;
while (l1 && l2) {
if (l1->val <= l2->val) {
p->next = l1;
l1 = l1->next;
p = p->next;
} else {
p->next = l2;
l2 = l2->next;
p = p->next;
}
}
while (l2) {
p->next = l2;
l2 = l2->next;
p = p->next;
}
while (l1) {
p->next = l1;
l1 = l1->next;
p = p->next;
}
return l3->next;
}
性能:
Runtime: 12 ms Memory Usage: 7.2 MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB