[LeetCode] 21. Merge Two Sorted Lists

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 21. 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 /**
 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 public:
11     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
12         ListNode *dummy = new ListNode(0);
13         ListNode *ret = NULL;
14         
15         
16         ListNode *p1 = l1;
17         ListNode *p2 = l2;
18         
19         ListNode *p = dummy;
20         
21         while(p1 && p2){
22             if (p1->val < p2->val){
23                 p->next = p1;
24                 p1 = p1->next;
25             }else{
26                 p->next = p2;
27                 p2 = p2->next;
28             }
29             p = p->next;
30         }
31         
32         p1 = (!p1) ? p2 : p1;
33         
34         while (p1){
35             p->next = p1;
36             // don‘t forget to move p1 !!
37             p1 = p1->next;
38             p = p->next;
39         }
40         
41         ret = dummy->next;
42         delete dummy;
43         return ret;
44     }
45 };

 

以上是关于[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