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

LeetCode – Refresh – Merge Two Sorted Lists

时间:2015-03-21 08:37:15      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

Iterative:

 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         if (!l1) return l2;
13         if (!l2) return l1;
14         ListNode *result = new ListNode(0);
15         ListNode *runner = result;
16         while (l1 || l2) {
17             int tmp1 = INT_MAX, tmp2 = INT_MAX;
18             if (l1) {
19                 tmp1 = l1->val;
20             }
21             if (l2) {
22                 tmp2 = l2->val;
23             }
24             if (tmp1 < tmp2) {
25                 runner->next = l1;
26                 l1 = l1->next;
27             } else {
28                 runner->next = l2;
29                 l2 = l2->next;
30             }
31             runner = runner->next;
32         }
33         return result->next;
34     }
35 };

 

Recursive:

 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         if (!l1) return l2;
13         if (!l2) return l1;
14         ListNode *result;
15         if (l1->val < l2->val) {
16             result = l1;
17             result->next = mergeTwoLists(l1->next, l2);
18         } else {
19             result = l2;
20             result->next = mergeTwoLists(l1, l2->next);
21         }
22         return result;
23     }
24 };

 

LeetCode – Refresh – Merge Two Sorted Lists

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4355097.html

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