【数据结构】判断两个链表是否相交若相交求交点

单链表的实现https://blog.csdn.net/weixin_41892460/article/details/82855823

1.假设链表不带环

思路:两个不带环的链表相交,则最后一个结点一定相同。


int CheckCross(pList list1, pList list2)
{
	if (NULL == list1 || NULL == list2)
		return 0;
	//遍历到最后一个节点
	while (list1->next)
	{
		list1 = list1->next;
	}
	while (list2->next)
	{
		list2 = list2->next;
	}
	if (list1 == list2)
	{
		return 1;
	}
	else
	{
		return 0;
	
}

**思路:利用快慢指针,首先求出两个链表的长度差n-1,然后让长的链表先走n-1步。然后一起走,相同的地方就是交点。**
pNode GetCrossNode(pNode list1, pList list2)
{
	if (NULL == list1 || NULL == list2)
		return 0;
	int size1 = 0;
	int size2 = 0;
	int del = 0;
	pNode cur1 = list1;
	pNode cur2 = list2;
	while (cur1)
	{
		cur1 = cur1->next;
		size1++;
	}
	while (cur2)
	{
		cur2 = cur2->next;
		size2++;
	}
	del = size1 - size2;
	cur1 = list1;
	cur2 = list2;
	if (del > 0)
	{
		while (del--)
		{
			cur1 = cur1->next;
		}
	}
	else
	{
		while (del++)
		{
			cur2 = cur2->next;
		}
	}
	while (cur1 != cur2)
	{
		cur1 = cur1->next;
		cur2 = cur2->next;
	}
	return cur1;
}

2.假设单链表带环

pNode GetCrossNodeH(pNode list1, pList list2)
{
	pNode fast = list1;
	pNode slow = list2;
	if (NULL == list1 || NULL == list2)
		return 0;
	while (fast&&fast->next)
	{
		fast = fast->next->next;
		slow = slow->next;
		if (slow == fast)
			return slow;
	}
	return NULL;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值