合并两个排序的链表

#include<iostream>
using namespace std;

struct MyNode
{
    int data;
    MyNode *next;
};

struct MyList
{
    MyNode *head;
};

void CreatMyList(MyList *ml,int n)
{
    if (NULL == ml )
    {
        return;
    }
    ml->head = new MyNode;
    MyNode *temp = ml->head;

    for (int i=n; i<n+10; i=i+2)
    {

        MyNode *mn = new MyNode;
        mn->data = i;
        mn->next = NULL;
        temp->next = mn;
        temp = temp->next;
    }
}


void DisplayMyList( const MyList * ml)
{
    if (NULL == ml||NULL == ml->head)
    {
        return;
    }
    MyNode *temp = ml->head->next;
    while(NULL != temp)
    {
        cout<<temp->data<<" ";
        temp = temp->next;
    }
    cout<<endl;

}

MyNode * ReMergeNode(MyNode *mn1, MyNode *mn2)
{
    if (NULL == mn1)
    {
        return mn2;
    }
    if (NULL == mn2)
    {
        return mn1;
    }
    MyNode *temp;
    if (mn1->data <= mn2->data)
    {
        temp = mn1;
        temp->next = ReMergeNode(mn1->next,mn2);
    }else
    {
        temp = mn2;
        temp->next = ReMergeNode(mn1,mn2->next);
    }

    return temp;
}

MyList * ReMergeList(MyList *ml1, MyList *ml2)
{
    if (NULL == ml1 || NULL == ml1->head || NULL == ml1->head->next)
    {
        return ml2;
    }
    if (NULL == ml2 || NULL == ml2->head || NULL == ml2->head->next)
    {
        return ml1;
    }

    if (NULL != ml1->head->next && NULL != ml2->head->next)
    {
        ml1->head->next = ReMergeNode(ml1->head->next,ml2->head->next);
        return ml1;

    }
}
void main(void)
{
    MyList *ml1 = new MyList;
    MyList *ml2 = new MyList;
    CreatMyList(ml1,0);
    CreatMyList(ml2,10);
    //ml1 = NULL;
    //ml2 = NULL;
    DisplayMyList(ml1);
    DisplayMyList(ml2);

    ml1 = ReMergeList(ml1,ml2);

    DisplayMyList(ml1);
    ml1 = MerList(ml1,ml2);
    DisplayMyList(ml1);

    getchar();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值