merge two sorted list

1 class Solution {
 2 public:
 3     ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         ListNode* root = new ListNode(-1);
 7         ListNode* ptr = root;
 8         while( l1!= NULL && l2 != NULL )
 9         {
10            if( l1->val <= l2->val )
11            {
12                 ptr->next = l1;
13                 ptr = ptr->next;
14                 l1 = l1->next;
15            }   
16            else
17            {
18                 ptr->next = l2;
19                 ptr = ptr->next;
20                 l2 = l2->next;            
21            }
22         }
23         if( l1 != NULL )
24             ptr->next = l1;
25         if( l2 != NULL )
26             ptr->next = l2;
27         
28         return root->next;
29         
30     }
31 };
1 class Solution {
 2 public:
 3     ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if( !l1 && !l2 ) return NULL;
 7         if( !l1 ) return l2;
 8         if( !l2 ) return l1;
 9         ListNode *h = new ListNode(0);
10         
11         h -> next = l1;
12         ListNode *p = h;
13         
14         while( l1 && l2 )
15         {
16             if( l1->val <= l2->val)
17             {
18                 p = p->next;
19                 l1 = l1->next;
20             }
21             else
22             {
23               
24                 p -> next = l2;
25                 l2 = l2 -> next;
26                 p -> next -> next = l1  ;              
27                 p = p->next;
28             }
29         }
30         if( l2 )  p->next = l2;
31         return h->next;
32         
33     }
34 };

原文链接: https://www.cnblogs.com/jumpinGGrass/p/3171406.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/94604

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 上午2:42
下一篇 2023年2月10日 上午2:42

相关推荐