euisblue
21. Merge Two Sorted Lists

1class Solution { 2 public: 3 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 4 ListNode *head; 5 if (!l1) return l2; 6 if (!l2) return l1; 7 8 if (l1->val < l2->val) { 9 head = l1; 10 l1 = l1->next; 11 } 12 else { 13 head = l2; 14 l2 = l2->next; 15 } 16 17 ListNode *temp = head; 18 while (l1 && l2) { 19 if (l1->val < l2->val ) { 20 temp->next = l1; 21 l1 = l1->next; 22 } else { 23 temp->next = l2; 24 l2 = l2->next; 25 } 26 temp = temp->next; 27 } 28 29 while (l1) { 30 temp->next = l1; 31 temp = temp->next; 32 l1 = l1->next; 33 } 34 35 while (l2) { 36 temp->next = l2; 37 temp = temp->next; 38 l2 = l2->next; 39 } 40 41 return head; 42 } 43};