LeetCode 面试题 02.08. 环路检测

题目链接:https://leetcode-cn.com/problems/linked-list-cycle-lcci/ 

给定一个有环链表,实现一个算法返回环路的开头节点。
有环链表的定义:在链表中某个节点的next元素指向在它前面出现过的节点,则表明该链表存在环路。

示例 1:

输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。

示例 2:

输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。

示例 3:

输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。

 1 struct ListNode *detectCycle(struct ListNode *head) {
 2     struct ListNode *fast=head,*slow=head;
 3     while(fast&&fast->next){
 4         slow=slow->next;
 5         fast=fast->next->next;
 6         if(fast==slow) break;
 7     }
 8     if (fast==NULL||fast->next==NULL) return NULL;
 9     slow=head;
10     while(slow!=fast){
11         slow=slow->next;
12         fast=fast->next;
13     }
14     return fast;
15 }

 

posted @ 2020-03-07 09:47  wydxry  阅读(330)  评论(0编辑  收藏  举报
Live2D