题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
快慢指针
思路
如果链表中有环,则快慢指针必定会相遇,每次迭代,fast执行两次next,slow就执行一次next;
注意:Java在While循环中,判断fast执行两次后next是否为null时,需要先判断执行一次next是否非null
/** * 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 (head == null || head.next == null) return false; ListNode fast = head, slow = head; while(fast.next != null && fast.next.next != null && slow.next != null){ fast = fast.next.next; slow = slow.next; if(fast == slow) return true; } return false; } }