程序员面试金典 - 面试题 02.08. 环路检测(快慢指针)

1. 题目

给定一个有环链表,实现一个算法返回环路的开头节点。
有环链表的定义:在链表中某个节点的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
解释:链表中没有环。

进阶:
你是否可以不用额外空间解决此题?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 快慢指针,快的走两步,慢的走一步,若fast==slow则存在环
  • 然后慢指针回到原点,快慢都一次只走一步,再次相遇的点就是环的入口
  • 具体推导过程见:链表中环的检测
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *fast = head, *slow = head;
        while(fast && fast->next)
        {
        	fast = fast->next->next;
        	slow = slow->next;
        	if(fast == slow)
        		break;
        }
        if(!fast || !fast->next)
        	return NULL;
        slow = head;
        while(fast != slow)
        {
        	fast = fast->next;
        	slow = slow->next;
        }
        return fast;
    }
};

在这里插入图片描述

发布了685 篇原创文章 · 获赞 594 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/104610303