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

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

    Follow up:
    Can you solve it without using extra space?

     1 class Solution {
     2 public:
     3     bool isCycle(ListNode* head) {
     4         if (!head) {
     5             return false;
     6         }
     7         ListNode* slow = head;
     8         ListNode* fast = head;
     9         while (slow && fast) {
    10             slow = slow->next;
    11             if (!fast->next) return false;
    12             fast = fast->next->next;
    13             if (fast == slow) {
    14                 return true;
    15             }
    16         }
    17         return false;
    18     }
    19     
    20     ListNode *detectCycle(ListNode *head) {
    21         if (!isCycle(head)) return NULL;
    22         ListNode* dummy = new ListNode(0);
    23         dummy->next = head;
    24         ListNode* slow = dummy;
    25         ListNode* fast = dummy;
    26         while (slow && fast) {
    27             slow = slow->next;
    28             fast = fast->next->next;
    29             if (slow == fast) {
    30                 break;
    31             }
    32         }
    33         
    34         slow = dummy;
    35         while(slow != fast) {
    36             slow = slow->next;
    37             fast = fast->next;
    38         }
    39         return slow;
    40     }
    41 };
  • 相关阅读:
    Flexbox 可视化属性
    latex 数学公式
    迭代器模式 rx 应用
    小程序开发 easy-less 配置
    react-devtool 消息处理渲染 源码理解
    csrf jsonp
    koa1 源码详解1
    Immutable api example
    es6 ajax
    lodash 替换 underscore
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3646440.html
Copyright © 2011-2022 走看看