zoukankan      html  css  js  c++  java
  • LeetCode 142. Linked List Cycle 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?

    这道题和之前那道比较难的链表题目相比,难度略大,不仅仅需要判断出是否有环,而且需要找到环的入口节点,《剑指offer》上给出的解法是:

    1、先用双指针判断是否有环,如果没有,返回空指针;如果有,指针停在环中的某个节点

    2、让环中的指针开始走,得到环的长度N

    3、一个指针指向头部,另一个指针比他快N步,两个一起前进,重合地方就是环的入口节点;

    但是这里我们采用更简单的方法:

    1、 先用双指针判断是否有环,如果没有,返回空指针;如果有,指针停在环中的某个节点,设该节点指针为p1

    2、让p2指向head节点,p1和p2一起走,二者重节点就是链表入口节点,证明请参考:http://www.cnblogs.com/hiddenfox/p/3408931.html

     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         ListNode *fast = head, *slow = head;
    13         while (fast && fast->next)
    14         {
    15             slow = slow->next;
    16             fast = fast->next->next;
    17             if (slow == fast)
    18                 break;
    19         }
    20         if (!fast || !fast->next)
    21             return nullptr;
    22         slow = head;
    23         while (slow != fast)
    24         {
    25             slow = slow->next;
    26             fast = fast->next;
    27         }
    28         return fast;
    29     }
    30 };
  • 相关阅读:
    常用和实用的git命令,让你快速入门git
    如何获取电脑的IP和mac地址
    关于vue插件的使用和修改
    BullsEye游戏优化布局
    BullsEye游戏总结
    Android游戏小demo
    算法及相应算法应用之令牌桶算法
    php IDE之phpStorm使用小记
    php中openssl_encrypt方法
    mysql界面工具
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8305933.html
Copyright © 2011-2022 走看看