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

21. Merge Two Sorted Lists

时间:2018-04-16 11:05:00      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:lin   color   return   else   link   col   efi   一个   als   

 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 static int wing=[]()
10 {
11     std::ios::sync_with_stdio(false);
12     cin.tie(NULL);
13     return 0;
14 }();
15 
16 class Solution 
17 {
18 public:
19     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 
20     {
21         ListNode head(INT_MIN);
22         ListNode *prt=&head;
23         
24         while(l1&&l2)
25         {
26             if(l1->val<l2->val)
27             {
28                 prt->next=l1;
29                 l1=l1->next;
30             }
31             else
32             {
33                 prt->next=l2;
34                 l2=l2->next;
35             }
36             prt=prt->next;
37         }
38         prt->next= l1? l1:l2;
39         return head.next;
40     }
41 };

新建一个链表,把原链表的节点一个个摘下来比较,直到摘完一个,剩下的直接放到新链表末尾。

如果要求空间复杂度O(1),就要麻烦些了,要排除特殊情况。

21. Merge Two Sorted Lists

标签:lin   color   return   else   link   col   efi   一个   als   

原文地址:https://www.cnblogs.com/zhuangbijingdeboke/p/8854444.html

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