首页 > 代码库 > Merge Two Sorted Lists
Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
思路:
1 class Solution { 2 public: 3 ListNode *mergeTwoLists( ListNode *l1, ListNode *l2 ) { 4 if( !l1 ) { return l2; } 5 if( !l2 ) { return l1; } 6 ListNode *head = 0; 7 if( l1->val <= l2->val ) { 8 head = l1; 9 l1 = l1->next;10 } else {11 head = l2;12 l2 = l2->next;13 }14 ListNode *end = head;15 while( l1 && l2 ) {16 if( l1->val <= l2->val ) {17 end->next = l1;18 l1 = l1->next;19 } else {20 end->next = l2;21 l2 = l2->next;22 }23 end = end->next;24 }25 if( l1 ) {26 end->next = l1;27 } else {28 end->next = l2;29 }30 return head;31 }32 };
Merge Two Sorted Lists
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。