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

版权声明:本文为原创文章QWQ,如果有错误欢迎指正,转载请注明作者且附带网址 https://blog.csdn.net/Mercury_Lc/article/details/83018821
#include <bits/stdc++.h>

using namespace std;

struct node
{
    int data;
    struct node *next;
};
struct node *creat(int n)       
{
    struct node *head,*tail,*p;
    head=(struct node*)malloc(sizeof(struct node));
    head->next=NULL;
    tail=head;
    int i;
    for(i=0;i<n;i++)
    {
        p=(struct node*)malloc(sizeof(struct node));
        p->next=NULL;
        scanf("%d",&p->data);
        tail->next=p;
        tail=p;
    }
    return head;
}
int main()
{
    struct node *head,*head1,*head2,*p,*p1,*p2,*tail;
    head=(struct node*)malloc(sizeof(struct node));
    head->next=NULL;
    tail=head;
    int n,m;
    scanf("%d %d",&n,&m);
    head1=creat(n);
    head2=creat(m);
    p1=head1->next;
    p2=head2->next;
    free(head1);                  
    free(head2);
    while(p1&&p2)
    {
        if(p1->data<p2->data)
        {
            tail->next=p1;
            tail=p1;
            p1=p1->next;
            tail->next=NULL;
        }
        else
        {
            tail->next=p2;
            tail=p2;
            p2=p2->next;
            tail->next=NULL;
        }
    }
    if(p1) tail->next=p1;                
    else tail->next=p2;
    for(p=head->next;p!=NULL;p=p->next)
    {
        if(p==head->next) printf("%d",p->data);
    else printf(" %d",p->data);
    }
    return 0;

}

猜你喜欢

转载自blog.csdn.net/Mercury_Lc/article/details/83018821