zoukankan      html  css  js  c++  java
  • Linked List Cycle II

    由链表起点到两指针相遇的地方总长为k,则必一指针经过k长,另一指针经过2k长。设环长为r,则2k-k=nr.即k=nr

    设由链表起点到环起点为s,环起点到两指针相遇处长m,则k=s+m

                                                                                   nr=s+m

                                             则所求链表起点到环起点   s=nr-m=(n-1)r+(r-m)     ;    n=1,s=r-m

    即由汇聚点和链表起点同时移动指针,两指针会在环的开始处相遇!

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *detectCycle(ListNode *head) {
    12         if(head==NULL) return head;
    13         ListNode *p=head,*pre=head;
    14         while(p&&p->next)
    15         {
    16          
    17             head=head->next;
    18             p=p->next->next;
    19             if(p==head)
    20             {
    21                 while(pre!=p)
    22                 {
    23                     p=p->next;
    24                     pre=pre->next;
    25                 }
    26                 return pre;
    27             }
    28         }
    29         return NULL;
    30     }
    31 };
  • 相关阅读:
    网络设备安全需求规格
    web安全法则
    Write Hole 问题
    如何同步master的代码到fork分支代码
    Self assignment
    Uninitialized scalar variable
    Operands of different size in bitwise operation
    Insecure Compiler Optimization
    negative array index read
    Unintended sign extension
  • 原文地址:https://www.cnblogs.com/daocaorenblog/p/4893224.html
Copyright © 2011-2022 走看看