给定一个链表,判断它是否有环。
样例
给出 -21->10->4->5, 尾部链到序号为1的结点,返回 true
挑战
不要使用额外的空间
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
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) {
if(head == null || head.next == null) return false;
ListNode p = head, q = head;
while(p != null && q != null) {
if(p.next == null || q.next == null || q.next.next == null) {
return false;
}
p = p.next;
q = q.next.next;
if(p == q) {
return true;
}
}
return false;
}
}