LinkedList Cycle length
Execution time limit is 1 second
Runtime memory usage limit is 128 megabytes
Given a linked list. Find the length of its cycle. If there is no cycle, return -1.
Definition of a single linked list:
// Java class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } }
// C++ class ListNode { public: int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };
// C struct ListNode { int val; struct ListNode *next; };
Implement a function CycleLength that returns a length of a cycle. If there is no cycle, return -1.
// Java int CycleLength(ListNode head)
// C, C++ int CycleLength(ListNode *head)
Example
Function CycleLength returns -1 because this linked list does not contain a cycle.
Function CycleLength returns 3 - the length of the cycle (3 → 4 → 5 → 3).
Submissions 1K
Acceptance rate 37%