Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Tips:判断一个链表中是否有环。
思路:设置两个指针,一个快(fast)一个慢(slow),fast指针每次走两步,slow每次走一步。当两个指针相遇,即存在环。若链表中没有环,则fast指针先到达null;
public boolean hasCycle(ListNode head) { if (head == null || head.next == null) return false; boolean hasCy = false; ListNode fast = head; ListNode slow = head; while (fast!=null) { if(fast.next!=null){ fast=fast.next; if(fast.next!=null){ fast=fast.next; slow=slow.next; if (fast == slow) { hasCy = true; break; } }else return false; }else return false; } return hasCy; }