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 };
  • 相关阅读:
    Super
    多态
    方法覆盖 和toString方法的作用
    Static 静态+this
    构造方法 + 继承
    使用方法重载的优缺点
    Erlang 简介与样例分析
    Assassin's Creed 4: Black Flag --《刺客信条4; 黑旗》
    DEVIL MAY CRY V:《鬼泣5》
    Valiant Hearts: The Great War -- 《勇敢的心》
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3735017.html
Copyright © 2011-2022 走看看