The noticeable part is to verify both twoStepLoop is not null and twoStepLoop.next is not null either… as it jumps two steps and has a command like twoStepLoop.next.next.
/**
* 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){
return false;
}
ListNode oneStep = head;
ListNode twoStep = head.next.next;
while(twoStep != null && twoStep.next != null){
if(oneStep == twoStep){
return true;
}
oneStep = oneStep.next;
twoStep = twoStep.next.next;
}
return false;
}
}
没有评论:
发表评论