zoukankan      html  css  js  c++  java
  • LeetCode --- Linked List Cycle II

    题目链接

    题意: 给出单链表,判断是否存在环,如果存在要求输出环开始的结点.

    思路及证明:

    It is a famous known problem Hare and Tortoise.

    Length of head to cycle started node: x

    Length of the cycle: y

    Let hare run two steps while tortoise runs one step

    while both of them entered the cycle, the hare is definetly to overlap the tortoise at some node, we define it as m:

    The hare totally runs: x + ky + m The tortoise totally runs: x + ty + m Thus, ky = 2ty + x + m we have (x + m) mod y = 0 We can conclude that if the hare run more x steps, it will reach the cycle's starting node.

    附上代码:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *detectCycle(ListNode *head) {
    12         if (head == NULL || head->next == NULL) {
    13             return NULL;
    14         }
    15         ListNode *fast = head, *slow = head;
    16         bool flag = false;
    17         while (fast != NULL && fast->next != NULL) {
    18             slow = slow->next;
    19             fast = fast->next->next;
    20             if (slow == fast) {
    21                 flag = true;
    22                 break;
    23             }
    24         }
    25         if (!flag) {
    26             return NULL;
    27         } else {
    28             slow = head;
    29             while (slow != fast) {
    30                 slow = slow->next;
    31                 fast = fast->next;
    32             }
    33             return slow;
    34         }
    35     }
    36 };
  • 相关阅读:
    mysql 时间函数
    Excel名称管理
    Unicode中文和特殊字符的编码范围
    带有历史数据置顶的id列表查询
    汉字表示范围
    ASP.NET模拟http进行GET/POST请求
    ASP.NET AES-128-CBC加密解密(与php通讯)
    dapper.net 获取分页存储过程返回的多结果集
    微信网页版抓包登录
    js添加/移除/阻止事件
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3735017.html
Copyright © 2011-2022 走看看