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

Leetcode 21. Merge Two Sorted Lists

时间:2016-07-12 23:28:19      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

21. Merge Two Sorted Lists

  • Total Accepted: 138746
  • Total Submissions: 383218
  • Difficulty: Easy

 

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

 

迭代:

 1 class Solution {
 2 public:
 3     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
 4         ListNode* head=new ListNode(-1);
 5         ListNode* end=head;
 6         while(l1&&l2){
 7             if(l1->val<l2->val){
 8                 end->next=l1;
 9                 l1=l1->next;
10             }
11             else{
12                 end->next=l2;
13                 l2=l2->next;
14             }
15             end=end->next;
16         }
17         if(l1){
18             end->next=l1;
19         }
20         else{
21             end->next=l2;
22         }
23         return head->next;
24     }
25 };

 

Leetcode 21. Merge Two Sorted Lists

标签:

原文地址:http://www.cnblogs.com/Deribs4/p/5665072.html

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