Given a linked list, determine if it has a cycle in it.Follow up:
Can you solve it without using extra space?
判断链表有环交了两次才AC,循环体中判断two!=null后应该直接返回false,即two指空应当马上返回false.
/**
* 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 one = head;
ListNode two = head;
while(two != null)
{
one = one.next;
two = two.next;
if(two != null)two = two.next;
else return false;
if(one == two)return true;
}
return false;
}
}