java算法环路检测,环路检测丶Java教程网-IT开发者们的技术天堂

题目描述

82d77006364a570a4977f366ad54ead5.png

解题思路

c28fb81a1d4a206cdd73973c34be6cc7.png

图中紫色节点为相遇节点,若快慢指针相遇,必定满足如下关系:

我们使用两个指针,它们起始都位于链表的头部。随后慢指针每次向后移动一个位置,而快指针向后移动两个位置。如果链表中存在环,则快 指针最终将再次与 慢指针在环中相遇。

当慢指针进入环以后,慢指针还没走完一个环的时候,快指针必定与之相遇,此时快指针可能已经走了n次环了。因此走过的距离为:s=a+n*(b+c)+b

任意时刻,快指针走过的距离都是慢指针的两倍 所以 2*(a+b)=a+n*(b+c)+b 所以得出 a=nb+nc-b 即是 a=(n-1)b+nc 即是 a=c+(n-1)(b+c)

从3可知,慢指针走完a表示着快指针走完c加n-1圈周长,因此他们会在入口节点相遇。

解题代码如下

/**

* @description:

* @author: lilang

* @version:

* @modified By:1170370113@qq.com

*/

public class ListSolution {

public ListNode detectCycle(ListNode head) {

if (head == null) {

return null;

}

ListNode goFast, goSlow;

goFast = goSlow = head;

boolean isCycle = false;

while (goFast != null && goSlow != null) {

goFast = goFast.next;

if (goFast == null) {

break;

} else {

goFast = goFast.next;

}

goSlow = goSlow.next;

if (goFast == goSlow) {

isCycle = true;

break;

}

}

if (!isCycle) {

return null;

}

goSlow = head;

while (goFast != goSlow) {

goFast = goFast.next;

goSlow = goSlow.next;

}

return goSlow;

}

public static void main(String[] args) {

System.out.println(null == null);

}

}

解题方法二

直接记录节点是否访问过,如果访问过表示存在环,否则不存在。

public class Solution {

public ListNode detectCycle(ListNode head) {

ListNode pos = head;

Set visited = new HashSet();

while (pos != null) {

if (visited.contains(pos)) {

return pos;

} else {

visited.add(pos);

}

pos = pos.next;

}

return null;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值