1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 12 if(l1==NULL)return l2; 13 if(l2==NULL)return l1; 14 ListNode *l3,*head; 15 if(l1->val<l2->val) { 16 l3=l1; 17 l1=l1->next; 18 } 19 else { 20 l3=l2; 21 l2=l2->next; 22 } 23 head=l3; 24 while(l1!=NULL&&l2!=NULL) { 25 if(l1->val<=l2->val) { 26 l3->next=l1; 27 l1=l1->next; 28 l3=l3->next; 29 } 30 else { 31 l3->next=l2; 32 l2=l2->next; 33 l3=l3->next; 34 } 35 } 36 while(l1!=NULL) { 37 l3->next=l1; 38 l1=l1->next; 39 l3=l3->next; 40 } 41 while(l2!=NULL) { 42 l3->next=l2; 43 l2=l2->next; 44 l3=l3->next; 45 } 46 return head; 47 } 48 };