给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。
说明:不允许修改给定的链表。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle-ii
思路:
1、快慢指针
class Solution {public:ListNode *detectCycle(ListNode *head) {if (head == nullptr || head->next == nullptr) {return nullptr;}ListNode* fast = head;ListNode* slow = head;while (fast != nullptr) {slow = slow->next;// 这步很重要:当链表无环时,fast->next会为空if (fast->next == nullptr) {return nullptr;}fast = fast->next->next;if (slow == fast) {ListNode* firstMeetNode = head;while (firstMeetNode != slow) {firstMeetNode = firstMeetNode->next;slow = slow->next;}return firstMeetNode;}}return nullptr;}};
TIPS:
快慢指针相遇时,满足:distance[snow, 首个交点] = distance[head, 首个交点]
2、HashTable
std::Set
cur = head;
while (cur != nullptr) {
if (nodes.find(cur) == nodes.end()) {
return cur;
}
cur = cur->next;
}
return nullptr;
