Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
两个指针,一个一次走两步,一个一次走一步,相遇说明有环
/** * 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) { if(head == null){ return false; } ListNode fast = head, slow = head; while(fast.next != null && fast.next.next != null){ fast = fast.next.next; slow = slow.next; if(fast == slow){ return true; } } return false; } }