判断链表是否有环
解决思路:
使用快慢指针,快指针的针走两步(fast.next.next),慢指针走一步(slow.next),判断两指针是否重合
Java实现:
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (slow != null && fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}
}