[leetcode] 21. Merge Two Sorted Lists

来源:互联网 发布:c语言ascii码 编辑:程序博客网 时间:2024/05/20 05:47

Question:

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.

Solution:

直接模拟归并排序的合并部分,不过对象是链表指针,但是过程是一样的。
时间复杂度:O(n)
空间复杂度:O(1)

/** * 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) {        if (!l1 && !l2) return l1;        if (!l1) return l2;        if (!l2) return l1;        ListNode *ret;        if ((l1->val < l2->val)) {            ret = l1;            l1 = l1->next;        } else {            ret = l2;            l2 = l2->next;        }        ListNode *tmp = ret;        while (l1 && l2) {            if (l1->val < l2->val) {                tmp->next = l1;                l1 = l1->next;            } else {                tmp->next = l2;                l2 = l2->next;            }            tmp = tmp->next;        }        while (l1) {            tmp->next = l1;            l1 = l1->next;            tmp = tmp->next;        }        while (l2) {            tmp->next = l2;            l2 = l2->next;            tmp = tmp->next;        }        return ret;    }};
原创粉丝点击