MergeList

对应写的是严蔚敏P21算法2.2,是把2个非递减的线性表(顺序表和链表)进行合并,和归并排序不同。

#include<iostream>
#include<malloc.h>
using namespace std;
typedef  struct Node{
    int value;
    struct Node *next;
} Node;


Node* CreateLinklist(int len){
    Node* ahead=(Node*)malloc(sizeof(Node));
    ahead->next=NULL;
    Node* l=ahead;
    for(int i=0;i<len;i++){
        Node* p=(Node*)malloc(sizeof(Node));
        cin>>p->value;
        p->next=NULL;
        l->next=p;
        l=l->next;
    }
    return ahead;
}
//采用链表
Node* MergeLinkList(Node* ahead,Node* bhead){
    Node* head=(Node*)malloc(sizeof(Node));
    Node* r=head;
    head->next=NULL;
    Node* p=NULL;
    Node* q=NULL;
    if(ahead->next!=NULL)
        p=ahead->next;
    else{
        return bhead;
    }


    if(bhead->next!=NULL)
       q=bhead->next;
    else
        return ahead;


    while(p!=NULL && q!=NULL){
        if(p->value<q->value){
            r->next=p;
            r=r->next;
            p=p->next;
        }
        else{
            r->next=q;
            r=r->next;
            q=q->next;
        }
    }


    while(p!=NULL){
        r->next=p;
        r=r->next;
        p=p->next;
    }


    while(q!=NULL){
        r->next=q;
        r=r->next;
        q=q->next;
    }


    return head;
}
//采用数组
int* MergeList(int a[],int alen,int b[],int blen){
    int* t=(int*)malloc(sizeof(int)*(alen+blen));
    int* flag=t;
    int* r=t;
    int i=0,j=0;
    while( i<alen&& j<blen){
        if(a[i]<b[j]){
            *r=a[i];
            r++;
            i++;
        }
        else{
            *r=b[j];
            r++;
            j++;


        }
    }
    while(i<alen){
       *r=a[i];
        r++;
        i++;
    }
    while(j<blen){
        *r=b[j];
        r++;
        j++;


    }




    return flag;
}


int main(){
    //顺序表
    int a[]={1,3,5,7,9};
    int b[]={2,4,6,8};
    int alen=sizeof(a)/sizeof(a[0]);
    int blen=sizeof(b)/sizeof(b[0]);
    int *t=MergeList(a,alen,b,blen);
    int m=0;
    while(m<alen+blen){
        cout<<*t<<endl;
        t++;
        m++;
    }
    //链表
    //创建链表A
    cout<<"LinkList A:";
    Node* ahead=CreateLinklist(5);
    //创建链表B
    cout<<"LinkList B:";
    Node* bhead=CreateLinklist(4);
    //得到归并后的链表并遍历
    Node* head=MergeLinkList(ahead,bhead);
    Node* p=head;
    if(p->next!=NULL)
        p=p->next;
    else
        return 0;
    while(p!=NULL){
        cout<<p->value<<endl;
        p=p->next;
    }
    return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值