Leetcode141. Linked List Cycle
/**
* 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, fast = head.next;
while(fast!=null){
if(slow==fast) return true;
slow = slow.next;
if(fast.next==null||fast.next.next==null) return false;
fast = fast.next.next;
}
return false;
}
}
/**
* 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, fast = head.next;
while(fast!=slow){
if(fast==null||fast.next==null||fast.next.next==null) return false;
fast = fast.next.next;
slow = slow.next;
}
return true;
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle.
Memory Usage: 37.6 MB, less than 96.65% of Java online submissions for Linked List Cycle.

浙公网安备 33010602011771号