LeetCode之Linked List Cycle II

来源:互联网 发布:苏沉船 王晶 知乎 编辑:程序博客网 时间:2024/05/22 13:52
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */ /*这是到数学技巧题目,具体参考自:https://github.com/soulmachine/leetcode*/class Solution {public:    ListNode *detectCycle(ListNode *head) {        ListNode *fast(head), *slow(head);        while(fast != nullptr && fast->next !=nullptr){            fast = fast->next->next;            slow = slow->next;            if(fast == slow){                ListNode *slow2(head);                while(slow !=slow2){                    slow2 = slow2->next;                    slow = slow->next;                }                return slow;            }        }        return nullptr;    }};

0 0