您的位置:首页 > 其它

LeetCode——linked-list-cycle-ii

2017-06-25 15:59 323 查看

Question

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:

Can you solve it without using extra space?

Solution

这道题技巧性比较强,首先要判断是否有环,这个时候可以用slow-fast法(http://www.cnblogs.com/zhonghuasong/p/7077051.html),两个指针,一个一次性走一步,一个一次性走两步,如果有环的话,他们两个毕会相遇。

然后就是找入口,可以看到环的起点和终点之间相隔的节点个数就是环中的节点个数,那么首先需要统计环中节点的个数。 统计好以后,怎么让slow指针走到起点的时候,fast指针走到终点呢? 也就是他们之间的距离始终保持着环中节点的个数,做法就是让fast先走环中节点个数步,然后slow和fast一起走。

Code

class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == NULL)
return head;
ListNode* slow = head;
ListNode* fast = head;

//判断是否有环
while (1) {
slow = slow->next;
if (fast->next != NULL && fast->next->next != NULL) {
fast = fast->next->next;
} else {
return NULL;
}
if (slow == fast)
break;
}
//统计环中节点个数
int count = 1;
fast = fast->next;
while (slow != fast) {
count++;
fast = fast->next;
}

// 先走count步,然后一起走,相遇的地方即入口
fast = head;
slow = head;
while (count--)
fast = fast->next;
while (fast != slow) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: