Given a list, the list is determined whether a ring

Given a list, the list is determined whether a ring.

To show the list given ring, we integer pos connected to the end of the list to represent the position of the list (index starts from 0). If pos is -1, the ring is not on this list.
Here Insert Picture Description
Problem-solving ideas:
traversal pointer with speed, if equal returns true, otherwise returns false. But this is not necessarily the node as the entry point of the ring, the ring can only prove the existence of it.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
typedef struct ListNode Node;
bool hasCycle(struct ListNode *head) {
    Node* slow = head;
    Node* fast = head;
    while(fast && fast->next)
    {
        slow = slow->next;
        fast = fast->next->next;

        if(slow == fast)
            return true;
    }
    return false;
}
Published 34 original articles · won praise 0 · Views 1244

Guess you like

Origin blog.csdn.net/smilevampire/article/details/104087069