题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
使用快慢指针,slow和quick,一个走一步,一个走两步,有环必定会相遇,注意判空
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { if (null == head || head.next == null) { return false; } ListNode slow = head; ListNode quick = head; while (null != slow && null != quick) { slow = slow.next; if (null != quick.next) { quick = quick.next.next; if (null != slow && slow == quick) { return true; } } } return false; } }