Created
December 9, 2014 21:38
-
-
Save szagriichuk/1933444220bbf443017d to your computer and use it in GitHub Desktop.
Linked List 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
/** | |
* Definition for singly-linked list. | |
* class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { | |
* val = x; | |
* next = null; | |
* } | |
* } | |
*/ | |
public class Solution { | |
public boolean hasCycle(ListNode head) { | |
if(head == null) | |
return false; | |
ListNode slow = head; | |
ListNode fast = head; | |
while(fast!=null && fast.next!=null){ | |
slow = slow.next; | |
fast = fast.next.next; | |
if(slow.equals(fast)){ | |
return true; | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment