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 };
  • 相关阅读:
    hdu 4768 Flyer 二分
    hdu 4767 Bell
    hdu 4759 Poker Shuffle 二进制
    uva 12589
    zoj 3057 Beans Game 博弈论
    poj 2480 Longge's problem 积性函数
    重新启程
    【Luogu P1502】 窗口的星星
    【BZOJ1855】[Scoi2010] 股票交易
    【BZOJ1122】[POI2008] 账本BBB
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8305933.html
Copyright © 2011-2022 走看看