1. 程式人生 > >LeetCode 142 Linked List Cycle II

LeetCode 142 Linked List Cycle II

turn problem desc temp esc link pro 一個點 ref

LeetCode 142

每遍歷一個點,都要判斷起點到這個點的距離,和啟動點到這個點的next的距離。再比較一下就可以了。

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        
        ListNode* iter = head;
        
        int dis1=0;
        int dis2;
      
        while(iter!=NULL)
        {
            dis1++;
            iter = iter->next;
            
            ListNode* temp = iter;
            ListNode* iter2 = head;
            dis2=1;
            while(iter2!=NULL&&iter2!=temp)
            {
                dis2++;
                iter2=iter2->next;
            }
            
            if(dis1>=dis2)
                return iter;
        }
        return NULL;  
    }

LeetCode 142 Linked List Cycle II