#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct LinkedList{
int data;
LinkedList *next;
}LinkedList,*List;
int a[5]={1,2,3,4,5};
int b[5]={4,5,6,7,8};
int n=5;
void build(List &L1,List &L2){
L1=(List)malloc(sizeof(LinkedList));
L2=(List)malloc(sizeof(LinkedList));
LinkedList *s1;
LinkedList *s2;
LinkedList *r1=L1;
LinkedList *r2=L2;
for(int i=0;i<n;i++){
s1=(LinkedList *)malloc(sizeof(LinkedList));
s1->data=a[i];
r1->next=s1;
r1=r1->next;
s2=(LinkedList *)malloc(sizeof(LinkedList));
s2->data=b[i];
r2->next=s2;
r2=r2->next;
}
r1->next=NULL;
r2->next=NULL;
}
void show(List &L){
LinkedList *s=L->next;
while(s){
printf("%d ",s->data);
s=s->next;
}
}
List findCommen(List &L1,List &L2){
LinkedList *p1=L1->next;
LinkedList *p2=L2->next;
LinkedList *r=(List)malloc(sizeof(LinkedList));
LinkedList *r1; //我们这里建立一个新的链表用来存放公共的节点
r1=r;
r->next=NULL;
LinkedList *s;
while(p1){//把L1循环一遍,把L2循环L1节点个数遍
p2=L2->next;//重置p2
while(p2){
if(p1->data==p2->data){
s=(LinkedList *)malloc(sizeof(LinkedList));
s->data=p1->data;
s->next=NULL;
r1->next=s;
r1=r1->next;
}
p2=p2->next;
}
p1=p1->next;
}
r1->next=NULL;//最后给r1的next置空
return r;
}
int main(){
List L1;
List L2;
build(L1,L2);
show(L1);
printf("\n");
show(L2);
List r=findCommen(L1,L2);
printf("\n");
printf("r:");
show(r);
printf("\nL1和L2的结构没有改变:\n");
printf("L1:");
show(L1);
printf("\n");
printf("L2:");
show(L2);
return 0;
}