算法:两个有序链表的合并

2014-11-24 12:01:22 · 作者: · 浏览: 0

LeetCode OJ Problem:Merge Two Sorted Lists


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.

class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if(!l1)
            return l2;
        else if(!l2)
            return l1;
        ListNode *head, *r;
        if(l1->val < l2->val)
        {
             head = l1;
             l1 = l1->next;
        }
        else
        {
             head = l2;
             l2 = l2->next;
        }
        head->next = NULL;   
        r = head;
        while(l1 && l2)
        {
            if(l1->val < l2->val)
            {
                r->next = l1;
                r = l1;
                l1 = l1->next;
            }
            else
            {
                r->next = l2;
                r = l2;
                l2 = l2->next;
            }
            r->next = NULL;
        }
        if(!l1)
            r->next = l2;
        else if(!l2)
            r->next = l1;
        return head;
    }
};