随笔- 509  文章- 0  评论- 151  阅读- 22万 

Merge Two Sorted Lists

2013.12.22 03:24

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.

Solution:

  This is a FAQ in IT interview. Make sure you don't new any node, and watch out for any special cases like NULL pointer or what.

  Time complexity is O(m + n), where m and n are the lengths of two lists. Space complexity is O(1).

Accepted code:

复制代码
 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         // IMPORTANT: Please reset any member data you declared, as
13         // the same Solution instance will be reused for each test case.
14         if(l1 == nullptr){
15             return l2;
16         }else if(l2 == nullptr){
17             return l1;
18         }
19         
20         ListNode *l3, *head;
21         
22         if(l1->val <= l2->val){
23             l3 = l1;
24             l1 = l1->next;
25         }else{
26             l3 = l2;
27             l2 = l2->next;
28         }
29         l3->next = nullptr;
30         head = l3;
31         
32         while(l1 != nullptr && l2 != nullptr){
33             if(l1->val <= l2->val){
34                 l3->next = l1;
35                 l1 = l1->next;
36             }else{
37                 l3->next = l2;
38                 l2 = l2->next;
39             }
40             l3 = l3->next;
41             l3->next = nullptr;
42         }
43         
44         while(l1 != nullptr){
45             l3->next = l1;
46             l1 = l1->next;
47             l3 = l3->next;
48             l3->next = nullptr;
49         }
50         while(l2 != nullptr){
51             l3->next = l2;
52             l2 = l2->next;
53             l3 = l3->next;
54             l3->next = nullptr;
55         }
56         
57         return head;
58     }
59 };
复制代码

 

 

 posted on   zhuli19901106  阅读(173)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示