/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
public boolean hasCycle(ListNode head) {
if(head==null){
return false;
}
ListNode fast=head;
ListNode slow=head;
while(fast.next!=null && fast.next.next!=null){ //只有保证fast.next不为空,才能有fast.next.next
slow=slow.next;
fast=fast.next.next;
if(slow==fast){ //最终slow追上fast
return true;
}
}
return false;
}
}
[Microsoft] Linked List Cycle
最新推荐文章于 2024-04-28 16:03:45 发布