【问题描述】给定两个单链表,编写算法找出两个链表的公共结点。
【输入形式】
四行:
第一行:一个数字(第一个单链表中的元素个数)
第二行:第一个单链表中各个结点的值
第三行:一个数字(第二个单链表中的元素个数)
第四行:第二个单链表中各个结点的值
【输出形式】
两行:
第一行:两个单链表的公共元素个数
第二行:依次打印输出各个公共元素
【样例输入】
6
12 5 8 9 -23 16
4
16 21 9 3
【样例输出】
2
9 16
注:若两个链表无公共元素,则输出:
0
没有公共元素
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
int cnt=0,a[MAX];
typedef struct LNode{
int data;
struct LNode *next;
}LNode,* LinkList;
//创建单链表
void CreateList(LinkList &L,int n){//注意要使用C++编译器,C语言中不允许使用"&"
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
for(int i=0;i<n;i++){
LinkList p=(LinkList)malloc(sizeof(LNode));
scanf("%d",&p->data);
p->next=L->next;
L->next=p;
}
}
//寻找公共结点
void findCommonNodes(LinkList l1,LinkList l2){
LinkList p=l1->next;
while(p){
LinkList q=l2->next;
while(q){
if(p->data==q->data){
a[cnt++]=p->data;
}
q=q->next;
}
p=p->next;
}
}
//打印公共结点
void PrintCommonNodes(int n){
if(n==0){
printf("%d\n",0);
printf("没有公共元素");
}
else{
printf("%d\n",n);
for(int i=n-1;i>=0;i--){
printf("%d ",a[i]);
}
}
}
//销毁单链表
void DestroyList(LinkList L)
{
LinkList q,p=L;
while(p!=0){
q=p->next;
free(p);
p=q;
}
L=NULL;
}
int main(){
int m,n;
LinkList l1,l2;
scanf("%d",&m);
CreateList(l1,m);
scanf("%d",&n);
CreateList(l2,n);
findCommonNodes(l1,l2);
DestroyList(l1);
DestroyList(l2);
PrintCommonNodes(cnt);
return 0;
}