不用额外空间检查linked list是否有环。 快慢指针即可,如果有换,快指针肯定能追上慢指针,否则肯定不会。
/**
* 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) {
ListNode s1 = head;
ListNode s2 = head;
while( s2!=null )
{
if( s1.next==null || s2.next==null || s2.next.next==null )
{
return false;
}
s1 = s1.next;
s2 = s2.next.next;
if( s1 == s2 )
{
return true;
}
}
return false;
}
}