https://leetcode.com/problems/linked-list-cycle-ii/
给定一个链表,判断是否有环,并且返回环开始的那个ListNode
- 思路1
HashSet存下来每一个走过的路,一直遍历,当发现set中有,则表明有环
public ListNode detectCycle(ListNode head) {
Set<ListNode> se = new HashSet<ListNode>();
ListNode tmp = head;
se.add(tmp);
while (tmp != null && tmp.next != null) {
tmp = tmp.next;
if (se.contains(tmp)) {
return tmp;
}
se.add(tmp);
}
return null;
}
- 思路2
1.快慢指针,先确定有换
2.fast不变,把slow指针再从头开始,fast和slow同时走,再相交的地方就是环的起点
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
break;
}
}
if (fast == null || fast.next == null) {
return null;
}
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
网友评论