zoukankan      html  css  js  c++  java
  • 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?

    思路:

    在上一题的基础上,假设head到环入口的距离为a,相遇点到环入口的距离为b,换的周长为r,则第一次相遇时有

    2*(a+b) = a + b + nr

    a = nr - b

    也就是说如果从相遇点和head处同时出发两个指针,步数一样,那么就会在环入口相遇,据此可以获得入口的指针

    代码

        ListNode *detectCycle(ListNode *head) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(head == NULL)
                return NULL;
            if(head->next == NULL)
                return NULL;
            ListNode *slow = head, *fast = head;
            while(true){
                if(fast && fast->next){
                    fast = fast->next->next;
                }
                else{
                    return NULL;
                }
                slow = slow->next;
                if(fast == slow)
                    break;
            }
            ListNode *p1 = head, *p2 = slow;
            while(true){
                if(p1 == p2)
                    return p1;
                p1 = p1->next;
                p2 = p2->next;
            }
        }
  • 相关阅读:
    第3章 C++ I/O流技术
    第2章 C++模板技术
    第1章 C++编程技术
    第0章 目录
    判断鼠标移入移出方向设置
    获取数组最小值
    jquery里的宽度详解
    trigger,triggerhandler模拟事件
    表单验证 不能为负值或者字母
    arguments的用法
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3404691.html
Copyright © 2011-2022 走看看