Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 7, 2017 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/40d584503d4ed265b34adc273cca09cb to your computer and use it in GitHub Desktop.
Save InterviewBytes/40d584503d4ed265b34adc273cca09cb to your computer and use it in GitHub Desktop.
Check if a linkedlist has a cycle
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;
}
}
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