博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

LeetCode【21】 Merge Two Sorted Lists

Posted on 2015-04-21 22:44  NUST小文  阅读(110)  评论(0编辑  收藏  举报

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.

AC代码如下:

 

ListNode* merge(ListNode* l1,ListNode* l2,int f1,int f2)
{
    if(f1<f2)
        return merge(l2,l1,f2,f1);
    //f1>=f2
    //Insert l1 into l2
    ListNode* tmp1=l1;
    ListNode* tmp2=l2;
    for(;tmp2->next!=NULL;)
    {
        if(tmp1!=NULL && tmp1->val>=tmp2->val && tmp1->val<=tmp2->next->val )
        {
            ListNode* newNode = new ListNode(tmp1->val);
            newNode->next = tmp2->next;
            tmp2->next = newNode;
            tmp1 = tmp1->next;
        }
        else
            tmp2=tmp2->next;
    }
    tmp2->next = tmp1;
    return l2;
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 
{
    if(l1 == NULL && l2 == NULL)
        return NULL;
    else if(l1 == NULL)
        return l2;
    else if(l2 == NULL)
        return l1;
    else
    {
        int len1=0,len2=0;
        return merge(l1,l2,l1->val,l2->val);
    }

思路比较简单,考虑到在链表头插入元素稍麻烦一点,于是比较两个链表第一个值大小,将较大值所在的链表插入到较小值所在的链表。