美文网首页
双指针应用六:链表的环入口

双指针应用六:链表的环入口

作者: 程一刀 | 来源:发表于2021-05-10 09:41 被阅读0次

    题目地址: https://leetcode-cn.com/problems/linked-list-cycle-ii/

    题目描述: 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null
    参考代码:

    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
            ListNode *fast = head;
            ListNode *slow = head;
            while (fast != nullptr && fast->next != nullptr) {
                slow = slow->next;
                fast = fast->next;
                fast = fast->next;
                if (slow == fast) {
                    ListNode *index1 = head;
                    ListNode *index2 = fast;
                    while (index1 != index2) {
                        index1 = index1 ->next;
                        index2 = index2 ->next;
                    }
                    return  index1;
                }
            }
            return nullptr;
            
        }
    };
    
    

    参考链接: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0142.%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8II.md

    相关文章

      网友评论

          本文标题:双指针应用六:链表的环入口

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