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

在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int data;
    node *next;
};
int main()
{
    node *head1,*head2;
    head1=new node();
    head2=new node();
    head1->next=NULL;
    head2->next=NULL;
    int n,m;
    cin>>m>>n;
    node *p,*q;
    q=head1;
    for(int i=0;i<m;i++)
    {
        p=new node();
        cin>>p->data;
        p->next=q->next;
        q->next=p;
        q=p;
    }
    q=head2;
    for(int i=0;i<n;i++)
    {
        p=new node();
        cin>>p->data;
        p->next=q->next;
        q->next=p;
        q=p;
    }
    p = head1->next;
    q = head2->next;
    node *t=head1;
    delete head2;
    while(p!=NULL&&q!=NULL)
    {
        if(p->data<q->data)
        {
            t->next=p;
            t = p;
            p=p->next;
            //t->next=NULL;
        }
        else
        {
            t->next=q;
            t=q;
            q=q->next;
            //t->next=NULL;
        }
    }
    if(p)
    {
        t->next=p;
    }
    if(q)
    {
        t->next=q;
    }
    q=head1->next;
    while(q)
    {
        if(q->next!=NULL)
            cout<<q->data<<" ";
        else
            cout<<q->data<<endl;
        q=q->next;
    }
    return 0;
}
发布了65 篇原创文章 · 获赞 2 · 访问量 835

猜你喜欢

转载自blog.csdn.net/weixin_43797452/article/details/104826721