【数据结构】给定两个单链表,编写算法找出两个链表的公共结点

【问题描述】给定两个单链表,编写算法找出两个链表的公共结点。
【输入形式】
四行:
第一行:一个数字(第一个单链表中的元素个数)
第二行:第一个单链表中各个结点的值
第三行:一个数字(第二个单链表中的元素个数)
第四行:第二个单链表中各个结点的值
【输出形式】
两行:
第一行:两个单链表的公共元素个数
第二行:依次打印输出各个公共元素
【样例输入】
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;
	
} 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值