MCPcopy Create free account
hub / github.com/codedecks-in/LeetCode-Solutions / hasCycle

Method hasCycle

Java/linked-list-cycle.java:13–44  ·  view source on GitHub ↗
(ListNode head)

Source from the content-addressed store, hash-verified

11 */
12public class Solution {
13 public boolean hasCycle(ListNode head) {
14
15 if (head == null){
16 return false;
17 }
18
19 ListNode slowPtr = head;
20 ListNode fastPtr = head;
21
22 /** Approach
23
24 // 1. if no cycle exists AND
25 // a. if there are even number of nodes then fast pointer will be pointing to null.
26 // b. else there are odd number of nodes then fast pointer will be pointing to last node.
27
28 // 2. if slow pointer meet fast pointer that interprets there exists a loop
29 */
30
31 while (fastPtr != null && fastPtr.next != null) {
32
33 // move slow pointer one node at a time
34 slowPtr = slowPtr.next;
35
36 // move fast pointer two nodes at a time
37 fastPtr = fastPtr.next.next;
38
39 if (slowPtr == fastPtr)
40 return true;
41 }
42
43 return false;
44 }
45}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected