141 Linked List Cycle – Medium
Problem:
Thoughts:
Solutions:
/**
* 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 slower = head;
ListNode faster = head.next;
while ( slower != null && faster != null){
if (slower == faster)
return true;
slower = slower.next;
if (faster.next == null)
break;
faster = faster.next.next;
}
return false;
}// hasCycle
}Last updated