题目地址: https://leetcode-cn.com/problems/linked-list-cycle-ii/
题目描述: 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null
参考代码:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast = head;
ListNode *slow = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next;
fast = fast->next;
if (slow == fast) {
ListNode *index1 = head;
ListNode *index2 = fast;
while (index1 != index2) {
index1 = index1 ->next;
index2 = index2 ->next;
}
return index1;
}
}
return nullptr;
}
};
网友评论