思路:
两次循环,先去遍历链表A中的每个元素,然后拿这个元素去遍历链表B,如果相同,就插入链表C中
代码:
void getIntersection(LNode *A,LNode *B,LNode *&C){//不妨设数据元素类型为int
//1.创建头结点
C=(LNode*)malloc(sizeof(LNode));
C->next=NULL;
//2.p是用来遍历链表A,r是用来记录C链表的末尾
LNode *p,*r;
r=C;
p=A->next;
while(p){
if(isExisted(p->data,B)){
//尾插到C
LNode *s=(LNode*)malloc(sizeof(LNode));
s->data=p->data;
r->next=s;
r=s;
}
p=p->next;
}
r->next=NULL;
}
//用来判断一个元素是否存在于一个链表中
bool isExisted(int data,LNode *A){
//pass
LNode *p=A->next;
while(p){
if(p->data==data)
return true;
p=p->next;
}
return false;
}
测试:
//引入基本依赖库
#include<stdio.h>
#include <stdlib.h>
#include<math.h> //数学函数,求平方根、三角函数、对数函数、指数函数...
//定义常量 MAXSIZE
#define MAXSIZE 15
//用于使用c++的输出语句
#include<iostream>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode;
void createList(LNode *&L,int arr[],int length);
void printList(LNode *L);
void getIntersection(LNode *A,LNode *B,LNode *&C);
bool isExisted(int data,LNode *A);
void main(){
int a[]={1,3,5,7,9};
int b[]={2,4,3,5,7,6,8,10};
LNode *L1= new LNode();
L1->next=NULL;
createList(L1,a,5);
printList(L1);
cout<<endl;
LNode *L2= new LNode();
L2->next=NULL;
createList(L2,b,8);
printList(L2);
cout<<endl;
LNode *L = new LNode();
getIntersection(L1,L2,L);
printList(L);
}
void getIntersection(LNode *A,LNode *B,LNode *&C){//不妨设数据元素类型为int
//1.创建头结点
C=(LNode*)malloc(sizeof(LNode));
C->next=NULL;
//2.p是用来遍历链表A,t是用来记录C链表的末尾
LNode *p,*t;
t=C;
p=A->next;
while(p){
if(isExisted(p->data,B)){
//尾插到C
t->next=(LNode*)malloc(sizeof(LNode));
t=t->next;
t->next=NULL;
t->data=p->data;
}
p=p->next;
}
}
//用来判断一个元素是否存在于一个链表中
bool isExisted(int data,LNode *A){
//pass
LNode *p=A->next;
while(p){
if(p->data==data)
return true;
p=p->next;
}
return false;
}
void createList(LNode *&L,int arr[],int length){
LNode *q=L;//q指向末尾结点
for(int i=0;i<length;i++){
LNode *node=new LNode();//创建一个新结点
node->data=arr[i];//将数组元素的值放入新创建的结点中
q->next=node;//将新结点接到链表后面
q=q->next;//将q后移到末端
}
q->next=NULL;//这是一个好习惯
}
void printList(LNode *L){
LNode *p=L;//p为循环遍历指针
while(p->next){
cout<<p->next->data<<"\t";
p=p->next;
}
}