/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Mergetwolists (listnode* L1, listnode*L2) { if(l1==null&&l2==NULL)returnNULL; if(l1==NULL)returnL2; if(l2==NULL)returnL1; ListNode*Head; if(l1->val<=l2->val) {Head=L1; L1=l1->Next; } Else{Head=L2; L2=l2->Next; } ListNode* p=Head; while(l1&&L2) {ListNode* k= (l1->val<=l2->val)?L1:l2; P->next=K; P=p->Next; if(k==L1) L1=l1->Next; ElseL2=l2->Next; } if(L1) P->next=L1; if(L2) p->next=L2; returnHead; }};
This is very verbose, you can consider applying for a head node, and then the operation of L1, L2 can be merged together.
The recursive method is as follows:
classSolution { Public: ListNode* Mergetwolists (listnode* L1, listnode*L2) { if(!L1)returnL2; Else if(!L2)returnL1; ListNode* head=NULL; if(l1->val<=l2->val) {Head=L1; Head->next=mergetwolists (l1->next,l2); } Else{Head=L2; Head->next=mergetwolists (l1,l2->next); } returnHead; }};
Merge Sorted Lists