Given a linked list, determine if it has a cycle in it.
/**
* 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 || head.next == null || head.next.next == null) {
return false;
}
ListNode n1 = head.next;
ListNode n2 = head.next.next;
while (n1 != n2) {
if (n2.next == null || n2.next.next == null) {
return false;
}
n1 = n1.next;
n2 = n2.next.next;
}
return true;
}
}
244

被折叠的 条评论
为什么被折叠?



