您的位置:首页 > 其它

2018.1.8 LeetCode 21. Merge Two Sorted Lists 【链表的基本运用】

2018-01-08 15:09 567 查看

21. Merge Two Sorted Lists

Description

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.

Example:

Input: 1->2->4, 1->3->4

Output: 1->1->2->3->4->4

题意: 合并两个链表

分析: 新建一个链表,然后逐个判断即可,需要注意:

1、是否有头结点

2、l1,l2为空的情况

参考函数

class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
ListNode* res = NULL;
if(l1->val >= l2->val) {
res = l2;
l2 = l2->next;
} else {
res = l1;
l1 = l1->next;
}
ListNode* p = res; // point
while (l1 && l2) {
if(l1->val >= l2->val) {
p->next = l2;
l2 = l2->next;
} else {
p->next = l1;
l1 = l1->next;
}
p = p->next;
}
if(l1) {
p->next = l1;
} else {
p->next = l2;
}
return res;
}
};


如有错误或遗漏,请私聊下UP,thx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: