题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode next = head.next.next;
while (head!=null && next!=null && next.next!=null ){ // 需要判断当前节点,和下一个节点和下下一个节点不为空
if (head==next){ // 如果快指针和慢指针相等,则说明有环
return true;
}
head = head.next; // 慢指针
next = next.next.next; // 快指针
}
return false;
} 算法 文章被收录于专栏
数据结构和算法
查看13道真题和解析