142. Linked List Cycle II
Difficulty: Medium
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
思路
首先需要判断链表是否存在环,若存在,假设环有n个结点,定义两个指向链表头结点的指针,其中一个指针先向前移动n步,再两个指针以相同速度向前移动,当两指针相遇时,指向环的入口结点。
接下来的问题是得到环中的结点数,当判断链表是否存在环时,存在环时两指针相遇的结点一定是在环中,可以从该结点向前移动,当回到该结点时,移动步数为环中结点数。判断链表是否有环可以用141题代码,不过函数返回相遇的结点。
代码
[C++]
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *meetingNode = hasCycle(head);
if (meetingNode == NULL)
return NULL;
ListNode *pNode = meetingNode;
int lenofcycle = 1;
while (pNode->next != meetingNode) {
pNode = pNode -> next;
lenofcycle++;
}
ListNode *fast = head;
ListNode *slow = head;
for (int i = 0; i < lenofcycle; ++i)
fast = fast->next;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return fast;
}
ListNode *hasCycle(ListNode *head) {
if (head == NULL)
return NULL;
struct ListNode *slow = head->next;
if (slow == NULL)
return NULL;
struct ListNode *fast = slow->next;
while (fast != NULL && slow != NULL) {
if (fast == slow)
return fast;
slow = slow->next;
fast = fast->next;
if (fast != NULL)
fast = fast->next;
}
return NULL;
}
};