Iterative:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 12 if (!l1) return l2; 13 if (!l2) return l1; 14 ListNode *result = new ListNode(0); 15 ListNode *runner = result; 16 while (l1 || l2) { 17 int tmp1 = INT_MAX, tmp2 = INT_MAX; 18 if (l1) { 19 tmp1 = l1->val; 20 } 21 if (l2) { 22 tmp2 = l2->val; 23 } 24 if (tmp1 < tmp2) { 25 runner->next = l1; 26 l1 = l1->next; 27 } else { 28 runner->next = l2; 29 l2 = l2->next; 30 } 31 runner = runner->next; 32 } 33 return result->next; 34 } 35 };
Recursive:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 12 if (!l1) return l2; 13 if (!l2) return l1; 14 ListNode *result; 15 if (l1->val < l2->val) { 16 result = l1; 17 result->next = mergeTwoLists(l1->next, l2); 18 } else { 19 result = l2; 20 result->next = mergeTwoLists(l1, l2->next); 21 } 22 return result; 23 } 24 };
时间: 2024-10-21 03:29:40