[LeetCode] 21. Merge Two Sorted Lists

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

 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 };

 

posted @ 2017-02-06 13:46  Strawberry丶  阅读(151)  评论(0编辑  收藏  举报