判断两个链表是否相交

假设两个链表的头指针分别为h1,h2

  • 思路一

    将h1的尾节点的指针域指向h2的头结点,即将h2连接在h1的后面。如果两个链表相交,那么此时的h2肯定是个循环链表,否则还是一个单向链表。此时的问题就简化成判断此时的h2是否为循环链表。

 

代码实现

bool isIntersect(pNode h1, pNode h2)
{

	if(!h1 || !h2)
		return false;
	
	bool flag = false;
	pNode temp_h1 = h1;
	pNode temp_h2 = h2;

	//找到第一个链表的尾节点,将第二个链表挂在其后
	while(temp_h1->next != NULL)
		temp_h1 = temp_h1->next;
	temp_h1->next = h2;

	do 
	{
		temp_h2 = temp_h2->next;
	}while(temp_h2 && temp_h2 != h2);

	if(temp_h2 == h2)
		flag = true;

	//将链表恢复原样
	temp_h1->next = NULL;
	
	return flag;
}
  • 思路二

    如果两个单向链表相交,那么这两个链表的尾结点一定相同(地址相同)。

代码实现

bool isIntersect(pNode h1, pNode h2)
{

	if(!h1 || !h2)
		return false;
	
	pNode tail_h1 = h1;
	pNode tail_h2 = h2;

	while(tail_h1->next != NULL)
		tail_h1 = tail_h1->next;

	while(tail_h2->next != NULL)
		tail_h2 = tail_h2->next;

	if(tail_h1 == tail_h2)
		return true;
	return false;
}

 

参考书籍:《编程之美》

转载于:https://my.oschina.net/u/1469592/blog/269127

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值