• 7-16 两个有序链表序列的交集(20 分)


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

    输入格式:

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

    输出格式:

    在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL

    输入样例:

    1 2 5 -1
    2 4 5 8 10 -1
    

    输出样例:

    2 5
    

    代码:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct Node {
        int data;
        struct Node *Next;
    };
    struct Node *CNode() {
        int d;
        struct Node *head = (struct Node *)malloc(sizeof(struct Node)),*q;
        head -> Next = NULL;
        q = head;
        while(~scanf("%d",&d)&&d!=-1) {
            struct Node *p = (struct Node *)malloc(sizeof(struct Node));
            p -> data = d;
            p -> Next = NULL;
            q -> Next = p;
            q = p;
        }
        return head;
    }
    struct Node *Intersection(struct Node *a,struct Node *b) {
        a = a -> Next;
        b = b -> Next;
        struct Node *head = (struct Node *)malloc(sizeof(struct Node));
        head -> Next = NULL;
        struct Node *q = head;
        while(a && b) {
            if(a == NULL || a -> data > b -> data) {
                b = b -> Next;
            }
            else if(b == NULL || b -> data > a -> data) {
                a = a -> Next;
            }
            else {
                struct Node *p = (struct Node *)malloc(sizeof(struct Node));
                p -> Next = NULL;
                p -> data = b -> data;
                q -> Next = p;
                q = p;
                a = a -> Next;
                b = b -> Next;
            }
        }
        return head;
    }
    void printL(struct Node *a) {
        a = a -> Next;
        if(a == NULL) printf("NULL");
        int flag = 0;
        while(a) {
            if(flag)printf(" %d",a -> data);
            else printf("%d",a -> data);
            a = a -> Next;
            flag = 1;
        }
    }
    int main() {
        struct Node *a = CNode();
        struct Node *b = CNode();
        struct Node *c = Intersection(a,b);
        printL(c);
    }
  • 相关阅读:
    单例和静态类
    Aggregate
    lc.exe已退出代码为1
    MVC 使用entity framework 访问数据库 发布IIS
    MVC 发布
    Nhiberate (三)测试
    Nhiberate (二) 搭项目
    初次安装git配置
    十大Intellij IDEA快捷键(转)
    Git强制覆盖master分支
  • 原文地址:https://www.cnblogs.com/8023spz/p/7703862.html
Copyright © 2020-2023  润新知