LinkedList Distance to Cycle
Very easy
Execution time limit is 1 second
Runtime memory usage limit is 128 megabytes
Given a linked list. Find the distance from the head of the list to the node where cycle starts. 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 DistanceToCycle that returns the distance from the head of the list to the node where cycle starts. If there is no cycle, return -1.
// Java int DistanceToCycle(ListNode head)
// C, C++ int DistanceToCycle(ListNode *head)
Example
Function DistanceToCycle returns -1 because this linked list does not contain a cycle.
Function DistanceToCycle returns 2 - the distance from the head of the list to the node where cycle starts. (1 → 2 → 3).
Submissions 665
Acceptance rate 38%