lesson6-2 设计一个函数,可以取出链表A和链表B的公共元素

本文介绍了一种方法来设计一个函数,通过两次循环遍历链表A和B,查找并收集两个链表中的公共元素,将结果存入新的链表C。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:

两次循环,先去遍历链表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;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值