解题思路:
使用快慢指针,快指针能追上慢指针即有环;否则无环
package com.lulu.leetcode;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class C_hasCycle {
public boolean hasCycle(ListNode head) {
if(head==null){
return false;
}
if(head.next==null){
return false;
}
ListNode fn=head;
ListNode pn=head;
while(fn.next!=null && fn.next.next!=null){<span style="font-family: Arial, Helvetica, sans-serif;"> </span>
<pre name="code" class="html"> fn=fn.next.next;
pn=pn.next;
if(fn==pn){ return true; } } return false; }}