Created
December 9, 2014 21:47
-
-
Save szagriichuk/66f7b768480dc80dbd5d to your computer and use it in GitHub Desktop.
Linked List Cycle II
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 slow = head; | |
ListNode expected = head; | |
ListNode fast = head; | |
while(fast!=null && fast.next!=null){ | |
slow = slow.next; | |
fast = fast.next.next; | |
if(expected.equals(slow)) | |
return expected; | |
if(slow.equals(fast)){ | |
expected = expected.next; | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment