首页 > 其他 > 详细

21. Merge Two Sorted Lists

时间:2018-04-16 10:51:34      阅读:156      评论:0      收藏:0      [点我收藏+]
 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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!