美文网首页
linked-list-cycle-ii

linked-list-cycle-ii

作者: 美不胜收oo | 来源:发表于2018-12-06 23:38 被阅读0次

title: linked-list-cycle-ii
date: 2018-12-06 23:32:52
categories: LeetCode
tags: [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* slow = head;
        ListNode* fast = head;
        
        ListNode* start = head;
        ListNode* meet;
        while(fast != NULL && fast->next != NULL)
        {
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow)
            {
                meet = fast;
                break;
            }
        }
        
        if(fast == NULL || fast->next == NULL)
        {
            return NULL;
        }
        
        while(start != meet)
        {
            start = start->next;
            meet = meet->next;
        }
        
        return meet;
        
    }
};

相关文章

网友评论

      本文标题:linked-list-cycle-ii

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