原文題目
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
.
題目摘要
head
(鏈結串列的頭節點)。true
(表示存在環)或 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.
解題思路
slow
,每次移動一個節點;另一個是快指標 fast
,每次移動兩個節點。兩個指標都從鏈結串列的頭節點 head
開始。while
迴圈遍歷鏈結串列,條件是快指標 fast
和快指標的下一個節點 fast.next
都不為 null
。這確保了快指標能夠正常移動而不會超出鏈結串列的範圍。slow == fast
),則表示鏈結串列中存在環,直接返回 true
。fast
或 fast.next
為 null
),則表示鏈結串列中不存在環,返回 false
。null
,說明沒有環;如果慢指標和快指標相遇,則說明存在環。程式碼
class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head; //設立一個慢指標指向頭節點
ListNode fast = head; //設立一個快指標指向頭節點
//當塊指標和快指標下一個節點都不為null時
while (fast != null && fast.next != null) {
slow = slow.next; //慢指標移動一個節點
fast = fast.next.next; //快指標移動兩個節點
//如果慢指標與快指標相遇,則表示存在循環
if (slow == fast) {
return true;
}
}
return false; //如果快指標到達鏈結串列尾,則表示不存在循環
}
}
結論
在這個題目我用快慢指標來判斷鏈結串列中是否存在環。通過設置兩個指標,慢指標每次移動一個節點,而快指標每次移動兩個節點,若鏈結串列中存在環,則快指標最終會與慢指標相遇。透過這個題目的學習,我進一步加深了對鏈結串列結構的理解,並掌握了如何使用指標操作來解決問題。