【一题多解】 LeetCode142.环形链表 II

91 阅读1分钟

本文已参加[新人创作礼]活动,一起开启掘金之路。 原题目跳转 -> 142.环形链表 II

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode * judgecircle(struct ListNode *head) 
{
    if(head == NULL)    return 0;
    struct ListNode * fast ,* slow ;
    fast = slow = head;
    while(fast && fast -> next)
    {
        fast = fast -> next -> next ;
        slow = slow -> next ;
        if(fast == slow )    return slow;
    }
    return NULL;
}

struct ListNode *detectCycle(struct ListNode *head) 
{
    struct ListNode * meet = judgecircle(head);//(1)
    struct ListNode * cur = head;
    if(meet)//如果存在环
    {
        while(cur)//(2)
        {
            if(meet == cur)     return meet;//找到就返回地址
            meet = meet -> next;
            cur = cur -> next; 
        }
    }
    else    return NULL;//找不到返回NULL
    return ;
}   

(1)判断是否有环存 如果有环存在 meet != NULL 如果无环 则是NULL 无法进入if 条件语句

(2)寻找相遇节点