PTA两个有序链表序列的交集

本文详细描述了如何使用C语言创建链表,以及如何合并两个链表并将节点数据按值排序后输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目如下,代码亲测能过

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

typedef struct list* List;
struct list{
    int data;
    List next;
};

int main()
{
    int i,n,flag = 0;
    List s1,s2,s3,t,S1,S2,S3;
    S1 = (List)malloc(sizeof(struct list));
    S2 = (List)malloc(sizeof(struct list)); 
    S3 = (List)malloc(sizeof(struct list));
    S3->next = NULL;
    s1 = S1; 
    s2 = S2;
    s3 = S3;
    
    while(1){
        scanf("%d",&n);
        if(n == -1) break;
        t = (List)malloc(sizeof(struct list));
        t->data = n;
        t->next = NULL;
        s1->next = t;
        s1 = s1->next;
    } 
    

    while(1){
    scanf("%d",&n);
        if(n == -1) break;
        t = (List)malloc(sizeof(struct list));
        t->data = n;
        t->next = NULL;
        s2->next = t;
        s2 = s2->next;
    } 
    s1 = S1; 
    s2 = S2; 

    
    while(s1->next != NULL && s2->next != NULL){
        if(s1->next->data == s2->next->data){
            s3->next = s1->next;
            s1 = s1->next;
            s2 = s2->next;
            s3 = s3->next;
        }else if(s1->next->data > s2->next->data){
            s2 = s2->next;
        }else{
            s1 = s1->next;
        }
}

 
    s3 = S3;
    if(s3->next == NULL){
        printf("NULL");
        return 0;
    }
    while(s3->next != NULL){
        if(!flag){
            flag = 1;
            printf("%d",s3->next->data);
        }else{
            printf(" %d",s3->next->data);
        }
        s3 = s3->next;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

—你的鼬先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值