/**
* 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.