leetcode 热题 Hot 100-3. 合并两个有序链表
- 题目
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
- 思路
- 把L2插入到L1,考虑是不是插入做L1的表头,如果不是表头要看L1当前节点的前一个节点
- 时间复杂度分析O(n)
- 代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
//把l2插入l1
//bug1: check l1 and l2 is NULL
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
ListNode* head = l1;
ListNode* beforeL1 = NULL;
ListNode* tempL2;
while(l2) {
//bug2: l1 must not empty ,then you can get l1->val
while (l1 && l2->val >= l1->val) {
beforeL1 = l1;
l1 = l1 -> next;
}
if (beforeL1 != NULL) {
beforeL1->next = l2;
} else {
head = l2;
}
tempL2 = l2->next;
l2->next = l1;
beforeL1 = l2;
l2 = tempL2;
}
return head;
}
};