这道题是判断链表中是否存在循环。因为题目中并没有要求不能修改原链表,就可以在循环过程中使当前节点指向某一个固定的节点,如果存在循环的话就会最终循环到该固定节点; 否则循环至Null。我指定的固定节点为head
public boolean hasCycle(ListNode head) {
if (head == null)
return false;
ListNode q, p = head.next;
while (p != null && p != head) {
q = p;
p = p.next;
q.next = head;
}
return p == head ? true : false;
}