您的位置:首页 > 职场人生

[LeetCode] Merge Two Sorted Lists

2013-01-27 20:49 357 查看
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!l1) return l2;
if (!l2) return l1;

ListNode *head = NULL;
if (l1->val < l2->val) {
head = l1;
l1 = l1->next;
} else {
head = l2;
l2 = l2->next;
}

ListNode *node = head;

while (l1 && l2) {
if (l1->val < l2->val) {
node->next = l1;
node = l1;
l1 = l1->next;
} else {
node->next = l2;
node = l2;
l2 = l2->next;
}
}

if (l1) node->next = l1;
if (l2) node->next = l2;

return head;
}
};


Small Case: 4ms

Large Case: 60ms

Time: O(n)

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