题目:Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up: Can you solve it without using extra space?
解析1:下面解题代码的思想及编写参考了网址https://github.com/soulmachine/leetcode#leetcode题解题目
解题代码如下:
//时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode* detectCycle(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast -> next) {
slow = slow -> next;
fast = fast -> next -> next;
if (slow == fast) {
ListNode *slow2 = head;
while (slow2 != slow) {
slow2 = slow2 -> next;
slow = slow -> next;
}
return slow2;
}
}
return nullptr;
}
};
解析2:设置一个unordered_map<ListNode*, int> visited
表示每个节点是否被访问,两次都被访问的第一个节点必然是环开始的地方。
解题代码如下:
//时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
ListNode* detectCycle(ListNode* head) {
unordered_map<ListNode*, int> visisted;
ListNode *cur = head;
while (cur) {
if (visited[cur] != 0) return cur;
else ++visited[cur];
cur = cur -> next;
}
return nullptr;
}
};