|
| 1 | +struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) { |
| 2 | + struct ListNode* l1_current = list1; |
| 3 | + struct ListNode* l2_current = list2; |
| 4 | + struct ListNode* head; |
| 5 | + // Set head to the pointer to the smaller first value of list1 and list2 |
| 6 | + if (l1_current && l2_current) { |
| 7 | + if (l1_current->val < l2_current->val) { |
| 8 | + head = l1_current; |
| 9 | + l1_current = l1_current->next; |
| 10 | + } else { |
| 11 | + head = l2_current; |
| 12 | + l2_current = l2_current->next; |
| 13 | + } |
| 14 | + |
| 15 | + // Trivial cases |
| 16 | + } else if (l1_current) { |
| 17 | + return list1; |
| 18 | + } else if (l2_current) { |
| 19 | + return list2; |
| 20 | + } else { |
| 21 | + return 0; |
| 22 | + } |
| 23 | + struct ListNode* current = head; |
| 24 | + while (1) { |
| 25 | + // We're finished |
| 26 | + if (!l1_current && !l2_current) { |
| 27 | + return head; |
| 28 | + } |
| 29 | + // Cases where we only have one list remaining |
| 30 | + // We can just assign the rest of the list to next here |
| 31 | + if (!l1_current) { |
| 32 | + current->next = l2_current; |
| 33 | + return head; |
| 34 | + } |
| 35 | + if (!l2_current) { |
| 36 | + current->next = l1_current; |
| 37 | + return head; |
| 38 | + } |
| 39 | + // Cases where we have two lists |
| 40 | + // Compare the values in each and add the smaller to the list being returned, |
| 41 | + // increasing pointers where necessary |
| 42 | + if (l1_current->val < l2_current->val) { |
| 43 | + current->next = l1_current; |
| 44 | + current = current->next; |
| 45 | + l1_current = l1_current->next; |
| 46 | + } else { |
| 47 | + current->next = l2_current; |
| 48 | + current = current->next; |
| 49 | + l2_current = l2_current->next; |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments