7-1 两个有序链表序列的合并 (10分)

练好速度

#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct Node *List;
struct Node
{
    int Data;
    List Next;
};
int main()
{
    int n;
    List head1=(List)malloc(sizeof(struct Node));
    List head2=(List)malloc(sizeof(struct Node));
    List L = head1,i,j,ans;
    while(cin >> n&&n!=-1){
        List tmp=(List)malloc(sizeof(struct Node));
        tmp->Data=n;
        tmp->Next=NULL;
        L->Next=tmp;
        L=tmp;
    }
    L = head2;
    while(cin >> n&&n!=-1){
        List tmp=(List)malloc(sizeof(struct Node));
        tmp->Data=n;
        tmp->Next=NULL;
        L->Next=tmp;
        L=tmp;
    }
    i = head1->Next;
    j = head2->Next;
    head2=head1;
    while(i||j){
        if((!j&&i)||i&&j&&i->Data<=j->Data){
            head2->Next=i;
            head2=i;
            i=i->Next;
        }
        else{
            head2->Next=j;
            head2=j;
            j=j->Next;
        }
    }
    head2=head1->Next;
    if(head2){
        while(head2){
            cout << head2->Data;
            if(head2->Next) cout << " ";
            head2=head2->Next;
        }
    }
    else{
        cout << "NULL";
    }
    return 0;
}

发布了10 篇原创文章 · 获赞 0 · 访问量 102

猜你喜欢

转载自blog.csdn.net/m0_46383408/article/details/104892896