数据结构实验之链表四:有序链表的归并


这道题的算法思想是建立一个空表,通过建立顺序链表,让指针依次指向原来两个链表中较小的元素。

代码如下:

#include <stdio.h>
#include <malloc.h>
struct node{/*单链表的定义*/
    int data;
    struct node* next;
};
struct node* Createlist(int n){/*顺序建立单链表*/
    struct node* head,*tail,*p;
    int i,d;
    head=(struct node*)malloc(sizeof(struct node));
    tail=head;
    for(i=1;i<=n;i++){
        p=(struct node*)malloc(sizeof(struct node));
        scanf("%d",&d);
        p->data=d;
        p->next=NULL;
        tail->next=p;
        tail=p;
    }
    return head;
};
struct node* Mergelist(struct node* head1,struct node* head2,struct node* head3){/*将两个一定顺序排列的单链表归并成一个有顺序的单链表*/
    struct node* tail;
    tail=head3;
    while(head1&&head2){/*将指针指向较小的元素构成新的单链表*/
        if (head1->data<head2->data){
           tail->next=head1;
           tail=head1;
           head1=head1->next;
        }
        else{
            tail->next=head2;
            tail=head2;
            head2=head2->next;
        }
    }
    if(head1){
        tail->next=head1;
    }
    if(head2){
        tail->next=head2;
    }
    return head3;
};
int main(){
    struct node*head1,*head2,*head3,*p,*q1,*q2;
    p=(struct node*)malloc(sizeof(struct node));
    head3=(struct node*)malloc(sizeof(struct node));/*为head3申请内存空间*/
    int i,j,m,n;
    scanf("%d %d",&m,&n);
    head1=Createlist(m);
    head2=Createlist(n);
    q1=head1->next;
    q2=head2->next;
    head3->next=NULL;/*建立空表*/
    head3=Mergelist(q1,q2,head3);
    for(p=head3->next;p!=NULL;p=p->next){
        if (p==head3->next)
            printf("%d",p->data);
        else
            printf(" %d",p->data);


    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值