1. 程式人生 > >領釦——141環形連結串列(快慢指標)

領釦——141環形連結串列(快慢指標)

給定一個連結串列,判斷連結串列中是否有環。

/**
 * 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 slow = head;
    ListNode fast = head.next;
    while (slow != fast) {
    //只要有一個為空,則無環
        if (fast == null || fast.next == null) {
            return false;
        }
        //移動快慢指標
        slow = slow.next;
        fast = fast.next.next;
    }
    return true;
    }
}