码迷,mamicode.com
首页 > 其他好文 > 详细

Merge Two Sorted Lists

时间:2014-08-25 18:38:04      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   div   log   amp   sp   

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 class Solution {
 2 public:
 3     ListNode *mergeTwoLists( ListNode *l1, ListNode *l2 ) {
 4         if( !l1 ) { return l2; }
 5         if( !l2 ) { return l1; }
 6         ListNode *head = 0;
 7         if( l1->val <= l2->val ) {
 8             head = l1;
 9             l1 = l1->next;
10         } else {
11             head = l2;
12             l2 = l2->next;
13         }
14         ListNode *end = head;
15         while( l1 && l2 ) {
16             if( l1->val <= l2->val ) {
17                 end->next = l1;
18                 l1 = l1->next;
19             } else {
20                 end->next = l2;
21                 l2 = l2->next;
22             }
23             end = end->next;
24         }
25         if( l1 ) {
26             end->next = l1;
27         } else {
28             end->next = l2;
29         }
30         return head;
31     }
32 };

 

Merge Two Sorted Lists

标签:des   style   blog   color   io   div   log   amp   sp   

原文地址:http://www.cnblogs.com/moderate-fish/p/3935219.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!