Given a list, the list is determined whether a ring.
To show the list given ring, we use an integer pos
to indicate a position connected to the end of the list of the list (starting with index 0). If pos
is -1
, there is no loop on this list.
Speed pointer method can be used to solve the problem
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ bool hasCycle(struct ListNode *head) { struct ListNode *slow = NULL; struct ListNode *fast = NULL; if (head == NULL || head->next == NULL) return false; slow = head; fast = head; while(fast->next && fast->next->next){ slow = slow->next; fast = fast->next->next; if (slow == fast) return true; } return false; }