Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?算法
给定一个单链表,判断链表是否有环。spa
设置两个指针(fast, slow),初始值都指向头,slow每次前进一步,fast每次前进二步,若是链表存在环,则fast一定先进入环,而slow后进入环,两个指针一定相遇.net
结点类指针
class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } }
算法实现类code
public class Solution { // 设置两个指针(fast, slow),初始值都指向头,slow每次前进一步,fast每次前进二步, // 若是链表存在环,则fast一定先进入环,而slow后进入环,两个指针一定相遇。 // (固然,fast先行头到尾部为NULL,则为无环链表)程序以下: public boolean hasCycle(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (slow == fast) { break; } } return !(fast == null || fast.next == null); } }