一点小失误,两次过
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 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 ListNode *ret = NULL; 15 ListNode *reti = NULL; 16 if (!l1) return l2; 17 if (!l2) return l1; 18 while (l1 && l2) { 19 if (!ret) { 20 ret = new ListNode(min(l1->val, l2->val)); 21 reti = ret; 22 if (l1->val < l2->val) l1 = l1->next; 23 else l2 = l2->next; 24 } 25 else { 26 ListNode *tmp = new ListNode(min(l1->val, l2->val)); 27 ret->next = tmp; 28 ret = ret->next; 29 if (l1->val < l2->val) l1 = l1->next; 30 else l2 = l2->next; 31 } 32 } 33 if (!l1) ret->next = l2; 34 if (!l2) ret->next = l1; 35 return reti; 36 } 37 };
下面这段没有造新listnode
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 ListNode *ans = NULL; 13 ListNode *p = ans; 14 if (!l1 && !l2) return ans; 15 while (l1 || l2) { 16 if (!l1) { 17 if (!ans) return l2; 18 p->next = l2; 19 break; 20 } 21 if (!l2) { 22 if (!ans) return l1; 23 p->next = l1; 24 break; 25 } 26 if (l1->val < l2->val) { 27 if (!ans) { 28 ans = l1; 29 p = ans; 30 } 31 else { 32 p->next = l1; 33 p = p->next; 34 } 35 l1 = l1->next; 36 } 37 else { 38 if (!ans) { 39 ans = l2; 40 p = ans; 41 } 42 else { 43 p->next = l2; 44 p = p->next; 45 } 46 l2 = l2->next; 47 } 48 } 49 return ans; 50 } 51 };
C#
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public int val; 5 * public ListNode next; 6 * public ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode MergeTwoLists(ListNode l1, ListNode l2) { 11 ListNode ans = null; 12 ListNode p = ans; 13 while (l1 != null || l2 != null) { 14 if (l1 == null) { 15 if (ans == null) return l2; 16 p.next = l2; 17 break; 18 } 19 if (l2 == null) { 20 if (ans == null) return l1; 21 p.next = l1; 22 break; 23 } 24 if (l1.val < l2.val) { 25 if (ans == null) p = ans = l1; 26 else { 27 p.next = l1; 28 p = p.next; 29 } 30 l1 = l1.next; 31 } 32 else { 33 if (ans == null) p = ans = l2; 34 else { 35 p.next = l2; 36 p = p.next; 37 } 38 l2 = l2.next; 39 } 40 } 41 return ans; 42 } 43 }