博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
判断两个单链表是否相交,若相交,求节点(链表不带环)
阅读量:2242 次
发布时间:2019-05-09

本文共 1136 字,大约阅读时间需要 3 分钟。

先理解一下题目的意思,单链表的相交和普通两条线的相交一样吗?

在这里插入图片描述
所以当我们把其换成节点就可以变成下面这样:

在这里插入图片描述

先判断链表是否相交,我们可以运用两个链表相交后就变成了一条链表这个特性来判断,因为如果两条链表相交,那么这两条链表的最后一个节点一定是同一个节点,否则不可能相交

//1表示有交点,0表示没有交点	int IsIntersection(Node *first1, Node *first2)	{		assert(first1);		assert(first2);		while (first1->next != NULL)		{			first1 = first1->next;		}		while (first2->next != NULL)		{			first2 = first2->next;		}		if (first1 == first2)		{			return 1;		}		return 0;	}

接下来,我们考虑交点的问题,如何才能找到交点?

两条链表在交点之后的长度肯定是一样的,在交点之前的长度是不一样的,我们可以计算出两条链表长度的差值k,然后让长的链表先走k步,再让两条链表同时走,当相同的时候,就表示走到交点了,这时候返回即可
在这里插入图片描述

int GetLength(Node *first)	{		assert(first);		int count = 0;		while (first != NULL)		{			count++;			first = first->next;		}		return count;	}	Node *IntersectionNode(Node *first1, Node *first2)	{		assert(first1);		assert(first2);		int count1 = GetLength(first1);		int count2 = GetLength(first2);		Node *longer = first1;		Node *shorter = first2;		int k = count1 - count2;		if (count1 < count2)		{			longer = first2;			shorter = first1;			k = count2 - count1;		}		while (k--)		{			longer = longer->next;		}		while (longer != shorter)		{			longer = longer->next;			shorter = shorter->next;		}		return longer;	}
你可能感兴趣的文章
理解事务的4种隔离级别
查看>>
常用正则匹配符号
查看>>
建议42: 让工具类不可实例化
查看>>
Java 异步机制与同步机制的区别
查看>>
hibernate的对象三种状态说明
查看>>
什么是N+1查询?
查看>>
Spring 接管 Hibernate 配置 延迟加载
查看>>
找出不在预定数组中的自然数
查看>>
String常见面试题
查看>>
直插,快排,堆排,归并排序的分析
查看>>
二叉树的各种操作(面试必备)
查看>>
oracle
查看>>
泛型与通配符详解
查看>>
BaseServiceImpl中的实现关键点
查看>>
Struts2中的session、request、respsonse获取方法
查看>>
如何理解MVC模型
查看>>
SpringMVC中乱码解决方案
查看>>
SpringMVC中时间格式转换的解决方案
查看>>
post和get请求相关知识点
查看>>
关于try finally 中的return语句的问题
查看>>