------------------------
只要设置两个指针,称为快慢指针,当链表没有环的时候快指针会走到null,当链表有环的时候快指针早晚会追上慢指针的。
AC代码:
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The first node of linked list. * @return: True if it has a cycle, or false */ public boolean hasCycle(ListNode head) { if(head==null || head.next==null) return false; ListNode fast=head.next.next; ListNode slow=head.next; while(true){ if(fast==null || fast.next==null){ return false; }else if(fast==slow || fast.next==slow){ return true; }else{ fast=fast.next.next; slow=slow.next; } } } }
题目来源: http://www.lintcode.com/zh-cn/problem/linked-list-cycle/