题目
给定一个链表,判断它是否有环。
给出 -21->10->4->5, tail connects to node index 1,返回 true
解题
两个指针不同步长走,当相遇了说明有环
public class Solution {
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
public boolean hasCycle(ListNode head) {
// write your code here
ListNode p1 = head;
if(p1==null || p1.next == null)
return false;
ListNode slow = head;
ListNode fast = head;
while(fast!=null && fast.next!=null&& fast.next.next!=null){
slow = slow.next;
fast = fast.next.next;
if(slow.val == fast.val)
return true;
}
return false;
}
}