单链表的合并

循环 解法一:

ListNode* MergeList(ListNode *L1,ListNode *L2)//合并两个单链表
{
    ListNode *newHead=NULL;
    ListNode *tail=NULL;
    if(L1==NULL)
    {
        return L2;
    }
    if(L2==NULL)
    {
        return L1;
    }
    if(L1->_data < L2->_data)
    {
        newHead=L1;
        L1=L1->_next;
    }
    else
    {
        newHead=L2;
        L2=L2->_next;
    }
    tail=newHead;
    while(L1 && L2)
    {
        if(L1->_data < L2->_data)
        {
            tail->_next=L1;
            L1=L1->_next;
        }
        else
        {
            tail->_next=L2;
            L2=L2->_next;
        }
        tail=tail->_next;
    }
    if(L1)
    {
        tail->_next=L1;
    }
    if(L2)
    {
        tail->_next=L2;
    }
    return tail;
}

 

递归 解法二:

ListNode* Merge1(ListNode *a,ListNode *b)
{
    if(a==NULL)
        return b;
    if(b==NULL)
        return a;
    ListNode *newhead=new ListNode;
    if(a->val<=b->val)
    {
        newhead=a;
        newhead->next=Merge1(a->next,b);
    }
    else
    {
        newhead=b;
        newhead->next=Merge1(a,b->next);
    }
    return newhead;
}

 

posted @ 2017-04-25 20:38  home普通的人  阅读(430)  评论(0编辑  收藏  举报