1. 程式人生 > >線性表——兩個有序連結串列序列的交集

線性表——兩個有序連結串列序列的交集

已知兩個非降序連結串列序列S1與S2,設計函式構造出S1與S2的交集新連結串列S3。

輸入格式:
輸入分兩行,分別在每行給出由若干個正整數構成的非降序序列,用−1表示序列的結尾(−1不屬於這個序列)。數字用空格間隔。

輸出格式:
在一行中輸出兩個輸入序列的交集序列,數字間用空格分開,結尾不能有多餘空格;若新連結串列為空,輸出NULL。

輸入樣例:
1 2 5 -1
2 4 5 8 10 -1
輸出樣例:
2 5

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <malloc.h>
#include <math.h>
using namespace std;

typedef struct LNode{
    int data;
    LNode *next;
}LNode, *Linklist;

void Init(Linklist &L)
{
    LNode *tmp;
    tmp = (Linklist)malloc(sizeof(LNode));
    tmp->next = NULL;
    L = tmp;
}

void Add(Linklist &L)
{
    int n;
    LNode *tmp, *p;
    tmp = L;
    while(~scanf("%d", &n))
    {
        if(n == -1) break;
        p = (Linklist)malloc(sizeof(LNode));
        p->data = n;
        p->next = NULL;
        tmp->next = p;
        tmp= p;
    }
}
Linklist componed(Linklist &L1, Linklist &L2)
{
    Linklist L;
    Init(L);
    LNode *tmp1, *tmp2, *tmp;
    tmp = L;
    tmp1 = L1->next;
    tmp2 = L2->next;
    while(tmp1 != NULL && tmp2 != NULL)
    {
        if(tmp1->data < tmp2->data)
        {
            tmp1 = tmp1->next;
        }
        else if(tmp2->data < tmp1->data)
        {
            tmp2 = tmp2->next;
        }
        else
        {
            tmp->next = tmp2;
            tmp = tmp2;
            //printf("%d\n", tmp->data);
            tmp2 = tmp2->next;
            tmp1 = tmp1->next;
        }
    }
    tmp->next = NULL;
    return L;
}
void print(Linklist L)
{
    int flag = 0;
    LNode *tmp = L->next;
    while(tmp != NULL)
    {
        if(flag) printf(" ");
        flag = 1;
        printf("%d", tmp->data);
        tmp = tmp->next;
    }
    printf("\n");
}
int main()
{
    Linklist L1, L2, L3;
    Init(L1);
    Init(L2);
    //Init(L3);
    Add(L1);
    Add(L2);
//    print(L1);
//    print(L2);
    L3 = componed(L1, L2);
    print(L3);
}