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);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM