keep learning, keep coding!
Problem - Linked List Cycle
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.
翻譯蒟蒻
判斷一個單向鏈表(linked list)是否包含循環。在鏈表中,每個節點都包含一個指向下一個節點的指針。如果在這個鏈表中有一個循環,就可以從某個節點開始,按照指針的方向一直遍歷,最終又回到某一個之前到過的節點。解這個問題的一種常見方法是使用兩個指針,一個快指針和一個慢指針,來追蹤鏈表。如果鏈表中存在循環,快指針最終會追上慢指針。
Example 1:
1
2
3Input: 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:
1
2
3Input: 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:
1
2
3Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
檢查一個鏈表是否有循環。
使用兩個指標,一個 fast 快指針(每次移動兩步)和一個 slow 慢指針(每次移動一步)。如果鏈表有循環,那麼 fast 快指針最終將追趕上 slow 慢指針,也就是 fast == slow 時,返回true
。如果鏈表沒有循環,那麼 fast 快指針會到鏈表的結尾,返回false
。
Solution - JavaScript
1 | /** |
Solution - Ruby
1 | def hasCycle(head) |
Solution - PHP
1 | function hasCycle($head) { |