[LeetCode] 21. Merge Two Sorted Lists

Posted NULL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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 };

 

以上是关于[LeetCode] 21. Merge Two Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode---21. Merge Two Sorted Lists

Leetcode 21. Merge Two Sorted Lists

LeetCode 21. Merge Two Sorted Lists

LeetCode算法-21Merge Two Sorted Lists

Leetcode 21. Merge Two Sorted Lists

[LeetCode] 21. Merge Two Sorted Lists