Description
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
合并两个有序链表,保证结果仍然有序,easy
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
auto p = l1, q = l2;
auto dummy = new ListNode(-1), pNode = dummy;
while (p || q) {
if (p == NULL) {
pNode->next = q;
return dummy->next;
}
if (q == NULL) {
pNode->next = p;
return dummy->next;
}
if (p->val < q->val) {
pNode->next = p;
p = p ->next;
} else {
pNode->next = q;
q = q->next;
}
pNode = pNode->next;
}
return dummy->next;
}
网友评论