题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
大佬们看看我这个有什么问题,最后一组测试用例无法通过,但最后一组测试用例无法完全输出...
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) return false;
//每次走一步
ListNode pre = head;
//每次走两步
ListNode nex = head.next;
//nex为空说明到末尾了,pre==nex说明追上了。到末尾了还未追上:没有环。追上了:有环。
while (pre != nex) {
if(pre == null || nex.next == null)
return false;
pre = pre.next;
nex = nex.next.next;
}
return true;
}
查看9道真题和解析