Last Updated on 2022-01-19 by Clay
題目
Given theheadof a linked list, return the node where the cycle begins. If there is no cycle, returnnull. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following thenextpointer. Internally,posis used to denote the index of the node that tail'snextpointer is connected to (0-indexed). It is-1if there is no cycle. Note thatposis not passed as a parameter. Do not modify the linked list.
Example 1:

Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:

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

Input: head = [1], pos = -1 Output: no cycle 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 <= 105posis-1or a valid index in the linked-list.
題目輸入一個鏈結串列,我們要判斷是否存在著迴圈(cycle)。如果存在則回傳迴圈接著的 node、不存在則回傳 NULL。
解題思路
(今天較為忙碌,晚點還有工作,先記錄著程式碼、而且這個解法也不夠好……)
C++ 範例程式碼
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
// Init
unordered_set<ListNode*> set;
while (head != nullptr) {
if (set.find(head) == set.end()) {
set.insert(head);
head = head->next;
}
else {
return head;
}
}
return nullptr;
}
};