合并两个有序链表

2、两个有序链表序列的合并

【问题描述】

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

【基本要求】

(1) 输入格式:

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

(2)输出格式:

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

(3)样例:

输入样例:

1 3 5 -1

2 4 6 8 10 -1

输出样例:

1 2 3 4 5 6 8 10

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

struct list{
    int data ;//节点数据域 
    struct list *next ;//节点指针域 
};//Linklist为指向结构体lNode 的指针类型
//void print(list L){
//    while(L->next!=NULL){
//        print("%-5d",L->next->data);
//        L =L->next;
//    }
//}

int main(int args,char *argv[]){
    struct list *head = (struct list *)malloc(sizeof(struct list));//创建头节点用malloc来分配空间
    head->next =NULL;
    struct list *p ; 
    
    struct list *L1 = (struct list *)malloc(sizeof(struct list));//创建头节点用malloc来分配空间
    L1->next =NULL;
    struct list *p3 ; 
        struct list *L2 = (struct list *)malloc(sizeof(struct list));//创建头节点用malloc来分配空间
    L2->next =NULL;
    struct list *p4 ; 
    p3 = L1 ;
    printf("请输入第一个链表的元素:");
    int num ;
    while (scanf("%d",&num)&&num!=-1){
    struct list *p1 = (struct list *)malloc(sizeof(struct list));//创建p1节点并分配内存空间
     p1->data=num;
     p3->next = p1 ;
     p1->next =NULL;
     p3 = p1;
    }
//    print(L);
    p3 = L1 ;
    while(p3->next!=NULL){
        printf("%-5d",p3->next->data);
        p3 =p3->next;
    }
    printf("请输入第二个链表的元素:");
    p4 = L2 ;
    while (scanf("%d",&num)&&num!=-1){
    struct list *p2 = (struct list *)malloc(sizeof(struct list));//创建p2节点并分配内存空间
     p2->data=num;
     p4->next = p2 ;
     p2->next =NULL;
     p4 = p2;
    }
        p4 = L2 ;
    while(p4->next!=NULL){
        printf("%-5d",p4->next->data);
        p4 =p4->next;
    }
    p3 = L1->next; p4 =L2->next;
    head =L1 ;
    p =head ;
    while (p3&&p4){
            if (p3->data<p4->data){
            p->next = p3; 
            p= p3 ;
            p3 = p3->next;
            } else if (p3->data==p4->data){
                p->next =p4; 
                p= p4; 
                p4 =p4->next;
                p3 =p3->next;
                
            }else{
                    p->next =p4; 
                p= p4; 
                p4 =p4->next;
            }
    }
    //将剩余非空字段插入到p所指的节点之后
    while(p3!=NULL||p4!=NULL) {
            p->next = p3?p3:p4;
            if (p3!=NULL){
                p3 =p3->next;
            }else {
                p4 =p4->next;
            }
    }

     p = head ; 
         printf("合并后的单链表为:"); 
     while(p->next!=NULL){
         
             printf("%-5d",p->next->data);
        p =p->next;
     }

新手小白请求指教

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值