Linked List Cycle II
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?
题目大意:
给定一个链表,如果该链表中含有环,则返回这个环开始的那个节点的地址,如果没有环,则返回NULL.
原题链接: https://leetcode.com/problems/linked-list-cycle-ii/
这个题目接Linked List Cycle, 也是快慢指针的运用.示意图如下:
如上图, 在环的前面,长度为a(即, 从头结点开始,走a步到环的入口), 环的周长为b(即,从环的入口开始,走b步回到入口处).
那么快慢指针每次分别走2步和1步,设走了x步相遇,则:
(2x−a)−(x−a)=nb;n=0,1,2,...
则,可知:
x=nb;n=0,1,2,...
那么,相遇点从环入口处计数,已经走了
nb−a
(步),换句话说, 这个时候再走
a
(步)就可以到环的入口处. 如果这个时候再有一个指针,从链表头开始走, 也正好走
综上,设快慢指针相遇点为meet, 令一个指针为p, p从头指针出开始走, 每次走一步, meet也跟随p每次走一步.那么他们会在环的入口处相遇.
代码如下:
// 有环的话,返回快慢指针相遇的地址;
// 无环的话,返回NULL
struct ListNode* judgeCycle(struct ListNode *head) {
int slowStep = 1;
int fastStep = 2;
struct ListNode* slow = head;
struct ListNode* fast = head;
while (true) {
for (int j = 0; j < fastStep; ++j) {
fast = fast->next;
if (NULL == fast) {
return NULL;
}
}
for (int i = 0; i < slowStep; ++i) {
slow = slow->next;
}
if (fast == slow) {
return fast;
}
}
}
struct ListNode *detectCycle(struct ListNode *head) {
if ((NULL == head) || (NULL == head->next)) {
return NULL;
}
struct ListNode* p = head;
struct ListNode* meet = judgeCycle(head);
if (NULL == meet) {
return NULL;
}
while (true) {
if (p == meet) {
return p;
}
p = p->next;
meet = meet->next;
}
}