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

[LeetCode] 21. Merge Two Sorted Lists

时间:2017-02-06 14:27:29      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:sts   http   com   for   int   init   logs   .com   技术   

技术分享

本题算法很简单,但利用引用保存头结点的方法值得学习,代码如下:

 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 {
11 public:
12     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
13     {
14         ListNode head(INT_MIN);
15         ListNode* res = &head;
16         while(l1 && l2)
17         {
18             if(l1->val < l2->val)
19             {
20                 res->next = l1;
21                 l1 = l1->next;
22             }
23             else
24             {
25                 res->next = l2;
26                 l2 = l2->next;
27             }
28             res = res->next;
29         }
30         res->next = l1 ? l1 : l2;
31         return head.next;
32     }
33 };

 

[LeetCode] 21. Merge Two Sorted Lists

标签:sts   http   com   for   int   init   logs   .com   技术   

原文地址:http://www.cnblogs.com/lca1826/p/6370071.html

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