chap2 7-3 兩個有序鏈表序列的交集 (20 分)

已知兩個非降序鏈表序列S1與S2,設計函數構造出S1與S2的交集新鏈表S3。

輸入格式:

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

輸出格式:

在一行中輸出兩個輸入序列的交集序列,數字間用空格分開,結尾不能有多餘空格;若新鏈表爲空,輸出NULL

輸入樣例:

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

輸出樣例:

2 5
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef int ElemType;
typedef struct LNode
{
    ElemType data;
    struct LNode *next;

}LNode,*LinkList;

LinkList PutL(void)
{
    LNode head;
    LinkList L = &head;
    head.next = NULL;
    int n;
    while(1)
    {
        cin>>n;
        if(n!=-1)
        {
            L->next = (LinkList)malloc(sizeof(LNode));
            L->next->data = n;
            L = L->next;
        }
        else
            break;
    }
    L->next = NULL;
    return head.next;
}
int main()
{
    LinkList S1 = PutL();
    LinkList S2 = PutL();
    LinkList S3 = S2;
    int f = 0;
    while(S1)
    {
        S2 = S3;
        while(S2)
        {
            if(S1->data == S2->data)
            {
                if(f)
                    cout<<" ";
                else
                    f = 1;
                cout<<S1->data;
                S3 = S2->next;
                break;
            }
            else if(S1->data < S2->data)
            {
                break;
            }
            S2 = S2->next;
            S3 = S2;
        }
        S1 = S1->next;
    }
    if(f==0)
        cout<<"NULL";
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章