描述
給定一個鏈表,判斷它是否有環。
樣例
給出 -21->10->4->5, tail connects to node index 1,返回 true
相關題目
帶環鏈表2 & 兩個鏈表的交叉
代碼實現
/**
* 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
*/
//快 慢 指 針
//快指針以慢指針二倍的速度移動,如果快慢指針指向同一地址,則返回true
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode fast = head.next;
ListNode slow = head;
while (fast != slow) {
if (fast == null || fast.next == null) {
return false;
} else {
fast = fast.next.next;
slow = slow.next;
}
}
return true;
}
}