We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Cycle Detection
- Discussions
Cycle Detection
Cycle Detection
Sort by
recency
|
35 Discussions
|
Please Login in order to post a comment
Java 8
This question does have bugs in some languages, such as JavaScript. I ran the following which is exactly equivalent to the working Python 3 solution already posted. That solution passes in Python, but it does not pass in JavaScrpt.
function hasCycle(head) { let node = head; const visited = {}; while (node) { if (visited[node]) return true; visited[node] = true; node = node.next; } return false; }
again this question is bugged... the example of the cycle:
1 can't point to both 1 and NULL!
At least this time the ro class compiles!
Only python works for me...
Floyd cycle approach
static boolean hasCycle(SinglyLinkedListNode head) { if (head == null || head.next == null) { return false; } SinglyLinkedListNode slow = head; SinglyLinkedListNode fast = head.next; while (fast != null && fast.next != null) { if (slow == fast) { return true; } slow = slow.next; fast = fast.next.next; } return false; }