Algorithm -leetcode-141. Endless chain

Topic Link circular linked list
method. 1: Method hash table, hash node visited with the recording, if the new access node in the hash table, it means a cycloalkyl
Method 2: Finger speed
1. fast pointer each take two steps, a slow pointer each take a step
2. If there is a ring, the faster the pointer will always circling in the ring
3. when the pointer reaches the slow ring entrance node, the pointer turns into a chase speed problem, fast pointer speed faster than slower pointer 1, must be able to chase on slow pointer
code is as follows:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    if (!head) {
        return false;
    }
    struct ListNode *fast, *slow;
    fast = head->next;
    slow = head;
    while (slow && fast) {
        if (fast == slow) {
            return true;
        }
        slow = slow->next;
        if (!fast->next) {
            return false;
        }
        fast = fast->next->next;
    }
    return false;
}

The first version of the code looks messy, optimize it according to the official recommended wording, a lot of cool

bool hasCycle(struct ListNode *head) {
    if (!head || !head->next) {
        return false;
    }
    struct ListNode *fast = head->next, *slow = head;
    while (slow != fast) {
        if (!fast || !fast->next) {
            return false;
        }
        slow = slow->next;
        fast = fast->next->next;
    }
    return true;
}

Method 3: Determine whether there is the list points to null elements, there will no ring, no ring there, because after the last element it may point to null
problem with this approach is to have the ring, it is necessary to set a closing conditions, is controlled by limiting the loop end condition is not the time limit 1000 in leetcode, 10000 times can be,

bool hasCycle(struct ListNode *head) {
    int count = 10000;
    while (count--) {
        if (!head) {
            return false;
        }
        head = head->next;
    }
    return true;
}

Guess you like

Origin www.cnblogs.com/xiaoshuai666/p/11387457.html