LeetCode 21. Merge Two Sorted Lists
1 class Solution { 2 public: 3 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 4 ListNode* head = new ListNode(0); 5 ListNode* res = head; 6 while(l1 != NULL && l2 != NULL){ 7 if(l1->val < l2->val){ 8 head->next = l1; 9 head = head->next; 10 l1 = l1->next; 11 } 12 else{ 13 head->next = l2; 14 head = head->next; 15 l2 = l2->next; 16 } 17 } 18 if(l1 != NULL) head->next = l1; 19 else if(l2 != NULL) head->next = l2; 20 return res->next; 21 } 22 };