zoukankan      html  css  js  c++  java
  • LeetCode OJ:Linked List Cycle II(循环链表II)

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

    Note: Do not modify the linked list.

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

    和前面那题类似,只不过这里要找到的是环开始的节点,看下面这张图(图是盗的):

    当fast以及slow指针在z处相遇的时候,可以得到一个计算式,关于两个指针走过的距离,有fast指针走过的距离是slow指针的2倍,那么有:

    a + b + c + b(fast) = 2 * (a + b)               =>                 a = c;

    那么从链表头在选一个指针,和slow指针一起走,正好可以在环的起始点处相遇,代码如下所示:

     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) return NULL;
    13         ListNode * slow = head;   
    14         ListNode * fast = head;
    15         while(slow && fast){
    16             slow = slow->next;
    17             fast = fast->next;
    18             if(fast)
    19                 fast = fast->next;
    20             if(fast && slow &&fast == slow)
    21                 break;
    22         }
    23         if(fast == NULL) return NULL;
    24         ListNode * start = head;
    25         while(slow != start){
    26             slow = slow->next;
    27             start = start->next;
    28         }
    29         return slow;
    30     }
    31 };

    还有一篇博客对这个问题还有类似的衍生问题描述的比较清楚,mark一下

  • 相关阅读:
    python变量及简单数据类型
    python函数小案例
    python字符串和列表小案例
    python循环输出
    Jmeter测试工具
    操作系统-进程管理~
    操作系统~
    组成原理第一章笔记~
    分时间段(年份或月份)统计,没有数字补0 Java(替代 MYSQL) 做法
    组成原理复习概略
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4936633.html
Copyright © 2011-2022 走看看