【LeetCode】 142. Linked List Cycle II C语言

来源:互联网 发布:win10 连接网络打印机 编辑:程序博客网 时间:2024/06/03 18:15


/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode *detectCycle(struct ListNode *head) {    if(head==NULL || head->next==NULL) return NULL;    struct ListNode *fast=head;    struct ListNode *slow=head;        while(1)    {        if(fast==NULL || fast->next==NULL) return NULL; //遇到null了,说明不存在环        slow=slow->next;        fast=fast->next->next;                if(fast == slow) break; //第一次相遇在Z点    }    slow=head; //slow从头开始走    while(slow!=fast)    {        slow=slow->next;        fast=fast->next;    }    return slow;}


0 0
原创粉丝点击