带环链表 II

作者: 杰米 | 来源:发表于2016-08-24 01:43 被阅读90次

给定一个链表,如果链表中存在环,则返回到链表中环的起始节点的值,如果没有环,返回null。

思路详解

class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins. 
     *           if there is no cycle, return null
     */
    ListNode *detectCycle(ListNode *head) {
        // write your code here
        if (!head || !head->next) {
            return NULL;
        }
        
        ListNode *fast = head;
        ListNode *slow = head;
        
        while(fast->next && fast->next->next) {
            fast = fast->next->next;
            slow = slow->next;
            
            if(fast == slow) {
                ListNode *temp = head;
                while(fast != temp) {
                    temp = temp->next;
                    fast = fast->next;
                }
                return fast;
            } 
        }
      
        
        return NULL;
    }
};

相关文章

  • 带环链表 II

    给定一个链表,如果链表中存在环,则返回到链表中环的起始节点的值,如果没有环,返回null。 思路详解 leetco...

  • lintcode-带环链表II

    给定一个链表,如果链表中存在环,则返回到链表中环的起始节点的值,如果没有环,返回null。

  • Linked List Cycle II(带环链表 II)

    问题 Given a linked list, return the node where the cycle b...

  • 带环链表

    版权声明:本文为博主原创文章,转载请注明出处。个人博客地址:https://yangyuanlin.club欢迎来...

  • 带环链表

    描述 给定一个链表,判断它是否有环。 样例 相关题目 带环链表2 & 两个链表的交叉 代码实现

  • 带环链表

    给定一个链表,判断它是否有环。 思路:快指针每次走两步慢指针每次走一步走到最后如果两指针相遇表示有环,若快指针走到...

  • 有环链表的判断以及入口点计算

    题意:给定一个单向链表,求判断该链表是否为带环链表并求出该环的入口点 来源地址:Chasiny 例如下图,一个带环...

  • 带环链表2

    描述 给定一个链表,如果链表中存在环,则返回到链表中环的起始节点的值,如果没有环,返回 null。 样例 代码实现

  • java判断链表是否有环(两种方式实现)

    判断链表是否为带环链表 方法一、快慢指针移动判断 首先如何判断链表是否有环,这个时候首先需要知道链表是否为空,如果...

  • LeetCode 142. Linked List Cycle

    @(LeetCode) 问题描述 给定一个链表,返回环入口节点。如果不存在环,则返回 null。 为了表示带环链表...

网友评论

    本文标题: 带环链表 II

    本文链接:https://www.haomeiwen.com/subject/rtinsttx.html