zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    导出 IIS 站点及配置
    redis
    mongo常用
    mongo分片集群
    mysql常用
    elk安装
    Oracle数据库迁移文档
    笔记
    ping 。sh
    光衰报警
  • 原文地址:https://www.cnblogs.com/shixinzei/p/12432737.html
Copyright © 2011-2022 走看看