-
-
Save InterviewBytes/40d584503d4ed265b34adc273cca09cb to your computer and use it in GitHub Desktop.
Check if a linkedlist has a cycle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interviewbytes.linkedlists; | |
public class HasCycle { | |
public boolean hasCycle(ListNode head) { | |
ListNode slow = head; | |
ListNode fast = head; | |
while (fast != null && fast.next != null) { | |
fast = fast.next.next; | |
slow = slow.next; | |
if (slow == fast) return true; | |
} | |
return false; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interviewbytes.linkedlists; | |
public class ListNode { | |
int val; | |
ListNode next; | |
ListNode(int x) { | |
val = x; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment