llllmz

导航

142. 环形链表 II

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *detectCycle(struct ListNode *head) {
    if(!head) return NULL;
    struct ListNode* slow=head,*fast=head;
    while(fast&&fast->next){
        slow=slow->next;
        fast=fast->next->next;
        if(slow==fast){
            struct ListNode* temp=head;
            while(temp!=slow){
                temp=temp->next;
                slow=slow->next;
            }
            return slow;
        }
    }
    return NULL;
}

 

posted on 2024-03-19 15:54  神奇的萝卜丝  阅读(16)  评论(0)    收藏  举报