由于是有序,所以通过 利用 分别指向两个待合并链表的指针 所指的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;
}