欣迪

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Constraints:

  • The number of the nodes in the list is in the range [0, 104].
  • -105 <= Node.val <= 105
  • pos is -1 or a valid index in the linked-list.

Follow up: Can you solve it using O(1) (i.e. constant) memory?

var hasCycle = function(head) {
    if (!head) return false
    let fast = head
    let current = head
    while(fast) {
        if (!fast.next) {
            return false
        } else {
            [fast, current] = [fast.next.next, current.next]
        }
        if (fast === current) {
            return true
        }
    }
    return false
};

判斷是否為迴圈,有一個常見的方法 Floyd判圈算法(Floyd Cycle Detection Algorithm),又稱龜兔賽跑算法(Tortoise and Hare Algorithm)。 這個 Youtube 影片有很詳細的解脫。

看完之後解法也呼之欲出。

需要一快一慢兩個變數。快速的變數每次往前推進兩個單位,慢數的則是每次往下一個單位,當出現盡頭時則不再檢測,排除是迴圈的可能。不段往下測試結果,只要兩個變數再次交疊在同一個位置,就可以判定是迴圈。

訂閱 IT-Monk

訂閱最新文章的發布消息! 😚😚😚
Loading

作者介紹 - 欣迪

欣迪

從設計到寫程式,發現自己有追求前端技巧的自虐傾向。不斷的踩坑,再從坑裡爬出來,慢慢對攀岩有點心得。 目前在多間公司擔任網站設計顧問。 同時也是網站架設公司負責人。