Created
January 27, 2015 08:09
-
-
Save the-fejw/535e4570425034229e3b to your computer and use it in GitHub Desktop.
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
/** | |
* 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