Skip to content

Instantly share code, notes, and snippets.

@the-fejw
Created January 27, 2015 08:09
Show Gist options
  • Save the-fejw/535e4570425034229e3b to your computer and use it in GitHub Desktop.
Save the-fejw/535e4570425034229e3b to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode p1 = head;
ListNode p2 = head;
boolean isCycle = false;
while (p2.next != null && p2.next.next != null) {
p1 = p1.next;
p2 = p2.next.next;
if (p1.equals(p2)) {
isCycle = true;
break;
}
}
if (!isCycle) return null;
p1 = head;
while (!p1.equals(p2)) {
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment