首页 > 其他 > 详细

[LeetCode] 21. Merge Two Sorted Lists

时间:2016-10-02 00:39:46      阅读:181      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/amadis/p/5926537.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!