[LeetCode]142.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?

分析:

首先使用快慢指针技巧,如果fast指针和slow指针相遇,则说明链表存在环路。当fast与slow相遇时,slow肯定没有遍历完链表,而fast已经在环内循环了n圈了(1<=n)设slow走了s步,则fast走了2s步(fast步数还等于s加上环在多转的n圈),设环长为r则:

                    2s = s + nr
                    s = nr

设整个链长L,环入口点与相遇点距离为a,起点到环入口点距离为x,则:

             x + a = s = nr = (n - 1)r + r = (n - 1)r + L - x
             x = (n - 1)r + L - x - a

L -x -a 为相遇点到环入口点的距离,由此可知,从链表开头到环入口点等于n - 1圈内环 + 相遇点到环入口点,于是我们可以从head开始另设一个指针slow2,两个慢指针每次前进一步,他们两个一定会在环入口点相遇。

这里写图片描述

代码:

    /**------------------------------------
    *   日期:2015-02-05
    *   作者:SJF0115
    *   题目: 142.Linked List Cycle II
    *   网址:https://oj.leetcode.com/problems/linked-list-cycle-ii/
    *   结果:AC
    *   来源:LeetCode
    *   博客:
    ---------------------------------------**/
    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;

    struct ListNode{
        int val;
        ListNode *next;
        ListNode(int x):val(x),next(NULL){}
    };

    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
            if(head == nullptr){
                return nullptr;
            }//if
            ListNode *slow = head,*fast = head,*slow2 = head;
            while(fast != nullptr && fast->next != nullptr){
                slow = slow->next;
                fast = fast->next->next;
                // 相遇点
                if(slow == fast){
                    while(slow != slow2){
                        slow = slow->next;
                        slow2 = slow2->next;
                    }//while
                    return slow;
                }//if
            }//while
            return nullptr;
        }
    };

运行时间

目录
相关文章
|
5月前
|
Java
Leetcode 114. Flatten Binary Tree to Linked List
思路也很简单,先把root的左子树(如有)变成单链表 leftlinkedlist,把root的右子树(如有)变成单链表 rightlinkedlist,再把root的右节点变成leftlikedlist,再把rightlinkedlist接到leftlinkedlist后面,代码如下。
20 1
|
5月前
|
C++
Leetcode Copy List with Random Pointer(面试题推荐)
给大家推荐一道leetcode上的面试题,这道题的具体讲解在《剑指offer》的P149页有思路讲解,如果你手头有这本书,建议翻阅。
26 0
|
5月前
Leetcode 19.Remove Nth Node From End of List
删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。
19 0
|
4月前
|
大数据 Java 程序员
「LeetCode合集」链表(List)及经典问题
「LeetCode合集」链表(List)及经典问题
27 0
LeetCode 141. 环形链表 Linked List Cycle
LeetCode 141. 环形链表 Linked List Cycle
LeetCode 234. 回文链表 Palindrome Linked List
LeetCode 234. 回文链表 Palindrome Linked List
LeetCode 206. 反转链表 Reverse Linked List
LeetCode 206. 反转链表 Reverse Linked List
|
1月前
|
存储 安全 Java
java集合框架及其特点(List、Set、Queue、Map)
java集合框架及其特点(List、Set、Queue、Map)
|
23天前
|
Java
Java使用List去重的四中方式
Java使用List去重的四中方式
16 6
|
1月前
|
Java
JAVA——List中剔除空元素(null)的三种方法汇总
JAVA——List中剔除空元素(null)的三种方法汇总

热门文章

最新文章