public Node getIntersectionNode(Node headA, Node headB) {
if (headA==null||headB==null) {
return null;
}
Node node1 = headA;
Node node2 = headB;
int headACount = 0;
int headBCount = 0;
while (node1.next!=null) {
node1 = node1.next;
++headACount;
}
while (node2.next!=null) {
node2 = node2.next;
++headBCount;
}
if (node1!=node2) {
return null;
}
int step = headACount-headBCount;
if (step>0) {
while (step>0) {
headA = headA.next;
step--;
}
} else {
step = -step;
while (step>0) {
headB = headB.next;
step--;
}
}
while (headA!=headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
}
LinkedList:两个单链表,返回第一个相交点,假设2个单链表都没有环
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 很多人猜测,毕加索、梵高这类绘画界巨匠之所以在艺术的历史长廊里为人所赞颂,或许是因为他们在学院派、古典派等写实画家...