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
归并两个有序链表,要求使用原有链表中的节点,所以只需要依次比较大小,改变原有节点的指向。 代码如下
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode *head = new ListNode(0), *l;
l = head;
while (l1 && l2) {
if (l1->val < l2->val) {
l->next = l1;
l1 = l1->next;
}
else {
l->next = l2;
l2 = l2->next;
}
l = l->next;
}
if (l1)
l->next = l1;
else if (l2)
l->next = l2;
return head->next;
}
};
本代码提交AC,用时8MS。
二刷。循环的时候用或运算也可以,代码更简洁。
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL)return l2;
ListNode* ans = new ListNode(0);
ListNode* root = ans;
while (l1 || l2) {
int v1 = l1 ? l1->val : INT_MAX;
int v2 = l2 ? l2->val : INT_MAX;
if (v1 != INT_MAX && v1 <= v2) {
root->next = l1;
root = root->next;
l1 = l1->next;
}
else if (v2 != INT_MAX && v2 < v1) {
root->next = l2;
root = root->next;
l2 = l2->next;
}
}
return ans->next;
}
};
本代码提交AC,用时8MS。
Pingback: LeetCode Merge k Sorted Lists | bitJoy > code