llllmz

导航

142. 环形链表 II C

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

结果:

posted on 2024-02-28 17:47  神奇的萝卜丝  阅读(15)  评论(0)    收藏  举报