首页 > 其他 > 详细

Merge Two Sorted Lists *****

时间:2015-04-17 17:38:18      阅读:209      评论: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.

***Note***

Why would it will cause ERROR when not deleting line 15~17 or changing line 12 to 

ListNode *pre_head = null; or  ListNode *pre_head;
 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 *pre_head = new ListNode(0);
13         ListNode *result = pre_head;
14         
15         //if(!l1 && !l2) return result;
16         //if(!l1 && l2) return l2;
17         //if(l1 && !l2) return l1;
18         
19         while(l1 || l2){
20             if(!l1){
21                 while(l2){
22                     result->next = l2;
23                     result = result->next;
24                     l2 = l2->next;
25                 }
26                 break;
27             }
28             else if(!l2){
29                 while(l1){
30                     result->next = l1;
31                     result = result->next;
32                     l1 = l1->next;
33                 }
34                 break;
35             }
36             else{
37                 if(l1->val <= l2->val){
38                     result->next = l1;
39                     l1 = l1->next;
40                 }
41                 else{
42                     result->next = l2;
43                     l2 = l2->next;
44                 }
45             }
46             result = result->next;
47             result->next = NULL;
48         }
49         return pre_head->next;
50     }
51 };

Merge Two Sorted Lists *****

原文:http://www.cnblogs.com/amazingzoe/p/4435435.html

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