7-2 两个有序链表序列的合并

7-2 两个有序链表序列的合并

分数 20

全屏浏览题目

切换布局

作者 DS课程组

单位 浙江大学

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。

输入格式:

输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。

输出格式:

在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL

输入样例:

1 3 5 -1
2 4 6 8 10 -1

输出样例:

1 2 3 4 5 6 8 10

代码长度限制

16 KB

时间限制

1500 ms

内存限制

128 MB

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

typedef int ElemType;
typedef int Status;

typedef struct LNode{
    ElemType data;
    struct LNode *next;
}*LinkList;

LinkList InitList_L(LinkList L){
    L=(LinkList)malloc(sizeof(struct LNode));
    L->next=NULL;
    return L;

}
void ListInsert_L(LinkList L,ElemType e){

   LinkList node;
    node=(LinkList)malloc(sizeof(struct LNode));
    node->data=e;
    node->next=NULL;
    L->next=node;

}
LinkList MergeList_L(LinkList A,LinkList B,LinkList C){
    LinkList a,b,c;
    a=A->next;
    b=B->next;
    C=c=A;
    while(a&&b){
        if(a->data<=b->data){
            c->next=a;
            c=a;
            a=a->next;
        }
        else {
            c->next=b;
            c=b;
            b=b->next;
        }
    }
    c->next=a?a:b;
    free(B);
    return C;
}
Status Print(LinkList L){
    LinkList p=L;
    if(p->next==NULL)
        return -1;
    p=p->next;
    int i=0;
    while(p){
        i++;
        if(i==1)
            printf("%d",p->data);
        else printf(" %d",p->data);
        p=p->next;
    }
}
int main(){
    LinkList A,B,C,a,b;
    int x;
    A = InitList_L(A);
    B = InitList_L(B);
    C = InitList_L(C);
   a = A;
   b = B;
    while(1){
        scanf("%d",&x);
        if(x==-1)
            break;

        ListInsert_L(A,x);
         A = A->next;

    }
    while(1){
        scanf("%d",&x);
        if(x==-1)
            break;
        ListInsert_L(B,x);
           B = B->next;
    }

  C =   MergeList_L(a,b,C);
  if(C->next==NULL)
    printf("NULL");
  else
    Print(C);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值