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

21. 合并两个有序链表

时间:2019-09-14 13:17:50      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:class   速度   temp   nbsp   空间   代码   color   sts   col   

好久没写链表了,写这个基础操作还是出现了一些bug,建议以后做题先写 伪代码,可以有逻辑性

 1 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
 2     if (l1 == nullptr)
 3         return l2;
 4     else if (l2 == nullptr)
 5         return l1;
 6     ListNode* temp1 = l1;
 7     ListNode* temp2 = l2;
 8     ListNode* next1 = nullptr;
 9     ListNode* next2 = nullptr;
10     while (temp1 != nullptr&&temp2 != nullptr)
11     {
12         if (temp1->val <= temp2->val && temp1->next)
13         {
14             if(temp1->next->val > temp2->val)
15             { 
16                 next2 = temp2->next;
17                 temp2->next = temp1->next;
18                 temp1->next = temp2;
19                 temp2 = next2;
20                 temp1 = temp1->next;
21             }    
22             else if(temp1->next->val <= temp2->val)
23                 temp1 = temp1->next;
24         }
25         else if(temp1->val<=temp2->val &&!temp1->next)
26         {                
27             temp1->next = temp2;
28             break;
29         }
30         else if (temp1->val > temp2->val)
31         {
32             next2 = temp2->next;
33             temp2->next = temp1;
34             temp1 = temp2;
35             temp2=next2;
36             l1 = temp1;    //bug
37         }
38     }
39     return l1;
40 }

 递归的解法,还行,感觉自己一直无法熟练运用递归,虽然递归空间和速度都不如迭代

 1 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
 2     if (l1 == nullptr)
 3         return l2;
 4     else if (l2 == nullptr)
 5         return l1;
 6     if (l1->val < l2->val)
 7     {
 8         l1->next = mergeTwoLists(l1->next, l2);
 9         return l1;
10     }
11     else
12     {
13         l2->next = mergeTwoLists(l1, l2->next);
14         return l2;
15     }
16 }

 

21. 合并两个有序链表

标签:class   速度   temp   nbsp   空间   代码   color   sts   col   

原文地址:https://www.cnblogs.com/zouma/p/11518728.html

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