LeetCode 142. Linked List Cycle II

来源:互联网 发布:淘宝卖家版本 编辑:程序博客网 时间:2024/06/03 19:19

Linked List Cycle II


题目思路

判断给定链表中是否存在环,如果存在环返回环的起点。

参考这篇文章。


题目代码:

/** * 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) {        if(head == nullptr || head->next == nullptr) return nullptr;        ListNode *fast = head;        ListNode *slow = head;                while(fast->next && fast->next->next){            slow = slow->next;            fast = fast->next->next;            if(slow == fast){                fast = head;                while(fast != slow){                    fast = fast->next;                    slow = slow->next;                }                return fast;            }        }        return nullptr;    }};