判断两个单链表是否相交及相交的第一个节点

/*
	问题: 
	1.判断两个单链表是否相交
	2.找出第一个相交节点
	解题思路:
	1.若连个链表相交则从相交节点开始以后节点都是一样的 
	2.通过链表长度判断然后去寻找 
*/

#include<stdlib.h>
#include<stdio.h>

/*
	创建节点 
*/
typedef struct STU
{
	char a;
	struct STU *next; 
}*SListNode;

SListNode ListA;
SListNode ListB;

/*
	创建链表A 
*/ 
SListNode createAlist(char a)
{
	SListNode headA=(SListNode)malloc(sizeof(struct STU));
	headA->a=a;
	headA->next=NULL;
	return headA;		
}

/*
	创建链表B 
*/ 
SListNode createBlist(char b)
{
	SListNode headB=(SListNode)malloc(sizeof(struct STU));
	headB->a=b;
	headB->next=NULL;
	return headB;
}

/*
	插入元素 
*/
SListNode insertElement(SListNode h,char a)
{
	SListNode p=h;
	SListNode n=(SListNode)malloc(sizeof(struct STU));
	if(n==NULL)
	{
		printf("ERROR:内存申请失败
");
		return NULL;
	} 
	n->a=a;
	n->next=NULL;
	while(p->next!=NULL)
	{
		p=p->next;
	}		
	p->next=n;
	return n;
}

/*
	打印链表 
*/ 
void printfList(SListNode h)
{
	int i=0;
	SListNode p=h;
	while(p!=NULL)
	{
		i++;
		printf("No.%d Element:%c
",i,p->a);
		p=p->next; 
	}
}

/*
	判断两链表是否相交
	并给出第一个相交节点元素 
*/
void IsIntersectant(SListNode A,SListNode B)
{
	char res;
	int  n=0;
	SListNode pa=A;
	SListNode pb=B;
	int Alength=0;
	int Blength=0;
	while(pa->next!=NULL)
	{
		Alength++;
		pa=pa->next;
	}	
	while(pb->next!=NULL)
	{
		Blength++;
		pb=pb->next;
	}
	if((pa->a==pb->a)&&(pa==pb))
	{
		printf("A链表和B链表相交
");
		pa=ListA;
		pb=ListB; 
		if(Alength==Blength)
		{
			while(Alength--)
			{
				if(pa==pb)
				{
					res=pa->a;
					break;
				}
				pa=pa->next;
				pb=pb->next;
			}
		}
		else if(Alength>Blength)
		{
			n=Alength-Blength;
			while((n)--)
			{
				pa=pa->next;		
			}	
			while(Blength--)
			{
				if(pa==pb)
				{
					res=pa->a;
					break;
				}
				pa=pa->next;
				pb=pb->next;
			}
		}
		else
		{
			n=Blength-Alength;
			while((n)--)
			{
				pb=pb->next;
			}
			while(Alength--)
			{
				if(pa==pb)
				{
					res=pa->a;
					break;
				}
				pa=pa->next;
				pb=pb->next;
			}
		}
		printf("相较于节点元素:%c",res);
	}
} 

/*
	创建相交的两条链表 
	相交节点Nnode
	相交节点元素:@ 
*/ 
void createIntersectantList(void)
{
	SListNode Nnode=(SListNode)malloc(sizeof(struct STU));
	Nnode->a='@';
	Nnode->next=NULL;
	insertElement(Nnode,'c');
 	insertElement(Nnode,'f');
 	insertElement(Nnode,'r');
 	insertElement(Nnode,'e');
 	insertElement(Nnode,'e');
	
	ListA=createAlist('A');
	insertElement(ListA,'1');
	insertElement(ListA,'4')->next=Nnode;
	
	ListB=createBlist('B');
	insertElement(ListB,'5');
	insertElement(ListB,'6');
	insertElement(ListB,'7');
	insertElement(ListB,'8')->next=Nnode;
	
	printfList(ListA);
	printfList(ListB);
	
	IsIntersectant(ListA,ListB);
}

int main(void)
{
	createIntersectantList();
}

  

原文地址:https://www.cnblogs.com/achao123456/p/6347526.html