您的位置:首页 > 其它

LeetCode 21 Merge Two Sorted Lists

2018-03-14 08:24 447 查看

LeetCode 21 Merge Two Sorted Lists

Description

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

代码

class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if (l1 == NULL)
return l2;

if (l2 == NULL)
return l1;

ListNode *ans = new ListNode(0);
ListNode *ret = ans;

if (l1->val < l2->val) {
ans->val = l1->val;
l1 = l1->next;
} else {
ans->val = l2->val;
l2 = l2->next;
}

while (l1 != NULL || l2 != NULL) {
if (l2 == NULL || l1 && l2 && l1->val < l2->val) {
ans->next = new ListNode(l1->val);
l1 = l1->next;
} else {
ans->next = new ListNode(l2->val);
l2 = l2->next;
}
ans = ans->next;
}
return ret;
}
};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: