classSolution{public:ListNode*mergeTwoLists(ListNode*l1,ListNode*l2){// Note: The Solution object is instantiated only once and is reused by each test case.
if(l1==NULL)returnl2;if(l2==NULL)returnl1;intval;if(l1->val<l2->val){val=l1->val;l1=l1->next;}else{val=l2->val;l2=l2->next;}ListNode*l=newListNode(val);ListNode*lcopy=l;intflag=0;while(true){if(l1==NULL){flag=1;break;}if(l2==NULL){flag=2;break;}if(l1->val<l2->val){val=l1->val;l1=l1->next;}else{val=l2->val;l2=l2->next;}ListNode*tmp=newListNode(val);lcopy->next=tmp;lcopy=lcopy->next;}if(flag==1){while(l2!=NULL){val=l2->val;l2=l2->next;ListNode*tmp=newListNode(val);lcopy->next=tmp;lcopy=lcopy->next;}}if(flag==2){while(l1!=NULL){val=l1->val;l1=l1->next;ListNode*tmp=newListNode(val);lcopy->next=tmp;lcopy=lcopy->next;}}returnl;}};