题意:判断链表中是否有环
思路:从起点开始,一个每次移动一步,另一个每次移动两步,如果相遇,说明有环
代码如下:
class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
if (null == head) return false;
ListNode fast = head.next;
while (fast != slow)
{
if (null == fast || null == slow) return false;
slow = slow.next;
if (null == fast.next) return false;
fast = fast.next.next;
}
return true;
}
}