码迷,mamicode.com
首页 > 其他好文 > 详细

19.1.29 [LeetCode 21] Merge Two Sorted Lists

时间:2019-01-29 14:57:05      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:nbsp   event   cli   should   sort   amp   splay   技术分享   fir   

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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
技术分享图片
 1 class Solution {
 2 public:
 3     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
 4         ListNode*head=new ListNode(0);
 5         ListNode*ans = head;
 6         while (l1&&l2) {
 7             if (l1->val < l2->val) {
 8                 head->next = l1;
 9                 l1 = l1->next;
10             }
11             else {
12                 head->next = l2;
13                 l2 = l2->next;
14             }
15             head = head->next;
16         }
17         if (l1)head->next = l1;
18         else if (l2)head->next = l2;
19         return ans->next;
20     }
21 };
View Code

 

19.1.29 [LeetCode 21] Merge Two Sorted Lists

标签:nbsp   event   cli   should   sort   amp   splay   技术分享   fir   

原文地址:https://www.cnblogs.com/yalphait/p/10333798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!