题目:
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.
解答:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**用例
NULL
NULL
1->NULL
NULL
NULL
1->NULL
1->NULL
2->NULL
2->NULL
1->NULL
2->3->4->5->6->NULL
3->5->6->NULL
2->4->NULL
3->5->NULL
**/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
ListNode* head = l1->val <= l2->val ? l1 : l2;
while (l1 && l2) {
while (l1->next && l1->next->val <= l2->val) {
l1 = l1->next;
}
if (l1->val <= l2->val) {
ListNode* tmp = l1->next;
l1->next = l2;
l1 = tmp;
if (!l1) break;
}
while (l2->next && l2->next->val < l1->val) {
l2 = l2->next;
}
if (l2->val < l1->val) {
ListNode* tmp = l2->next;
l2->next = l1;
l2 = tmp;
if (!l2) break;
}
}
return head;
}
};