2-12. 两个有序链表序列的交集(20)

由于是有序,所以通过 利用 分别指向两个待合并链表的指针 所指的data相互比较 进而求交集 相比顺序表 实现 效率高。

#include<iostream>
using namespace std;

typedef struct Node
{
        int data;
        Node *next;
}*LinkList;

LinkList CreatList()
{
        LinkList List, temp;
        List = new Node;

        List->next = temp =  NULL;
        int num;
        Node *Point = List;
        while( cin>>num && num!=-1 )
        {
                temp = new Node;
                temp->data = num;
                Point -> next = temp;
                Point = Point->next;
        }
        Point->next = NULL;
        return List;
}

void Print( LinkList List )
{
        if( List->next==NULL ){
            cout<<"NULL"<<endl;
            return ;
        }
        bool first = true;
        while( List->next !=NULL )
        {
            if( first ){
                cout<<(List->next)->data;
                first = false;
            }
            else
                cout<<" "<<(List->next)->data;
                List = List->next;
        }
        cout<<endl;
}

LinkList Mix( LinkList L1, LinkList L2 )
{
        LinkList Mixed = new Node;
        LinkList temp;
        Node *P1, *P2, *P3;
        P1=L1->next;
        P2=L2->next;
        P3 = Mixed;
        while( P1 && P2 )
        {
                if( P1->data < P2->data )
                        P1 = P1->next;
                else
                    if( P1->data > P2->data )
                        P2 = P2->next;
                else{
                     temp = new Node;
                     temp->data = P1->data;
                    P3->next = temp;
                    P1 = P1->next;
                    P2 = P2->next;
                    P3 = P3->next;
                }
        }
        P3->next = NULL;
        return Mixed;
}

int main()
{
        LinkList List1=CreatList();
        LinkList List2=CreatList();
        LinkList List3=Mix( List1, List2 );
        Print( List3 );
        return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值