这阵子浅写了几道题,刷到环形链表,第一眼还是比较难想的,在这里总结快慢指针的方法。
// 了解原理后,代码还是比较简单的,要注意细节
// 小细节
// 1. 避免都是头结点的情况
// 2. 避免都是 null 的情况
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
return true;
}
}
return false;
}
}
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
break;
}
}
if (slow != fast) {
return null;
}
fast = head;
while(slow != fast){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}