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

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
            ListNode *p1=head;
            ListNode *p2=head;
            if(!p1)
                return NULL;
            
            do{
                p1=p1->next;
                p2=p2->next;
                if(p2)
                    p2=p2->next;
            }while(p1&&p2&&p1!=p2);
            if(!p1||!p2)
                return NULL;
            p1=head;
            while(p1!=p2)
            {
                p1=p1->next;
                p2=p2->next;
            }
            return p1;
        }
    };

    note:

    开始时,两指针都指向head,之后再快步慢步走;

    假设head为A,环起始点为B,两指针相遇点为C,则LAB=LBC+n环周长;

  • 相关阅读:
    11.2
    11.1
    10.31JS中级
    10.24
    动画运动
    操作js的样式
    js
    js元素属性
    js轮播
    js计时器
  • 原文地址:https://www.cnblogs.com/jsir2016bky/p/5475066.html
Copyright © 2011-2022 走看看