首页 > 代码库 > LeetCode:Linked List Cycle

LeetCode:Linked List Cycle

题目描述:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

思路:初始化一个快指针fast,一个慢指针slow。快指针一次移动两个单位,慢指针一次移动一个单位。如果链表有环,则两指针必然会相遇。否则若fast指针遍历到NULL,则证明链表无环。


代码:

 bool hasCycle(ListNode *head) {
    ListNode * fast = head;
    ListNode * slow = head;
    while(fast != NULL && fast->next != NULL)
    {
        fast = fast->next->next;
        slow = slow->next;
        if(fast == slow)
            break;
    }
    if(fast == NULL || fast->next == NULL)
        return false;
    else
        return true;
    }
};


LeetCode:Linked List Cycle