思路
- 快慢指针相遇,即为有环
- 从head,和相遇点开始,一步步的next,再次相遇点即为环的起始点
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast = head;
ListNode *slow = head;
bool flag = false;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if (slow == fast) {
flag = true;
break;
}
}
if (flag == true) {
int pos = 1;
ListNode *reStart = head;
ListNode *crossover = slow;
while (reStart != crossover) {
reStart = reStart->next;
crossover = crossover->next;
pos++;
}
return reStart;
}
return NULL;
}
};

问题
- 空指针问题
- 超时因为我从head和slow->next开始的遍历,导致无法相遇。
- 总耗时16分钟