【LeetCode】142. 环形链表 II

leetcode题目链接 142. 环形链表 II
【LeetCode】142. 环形链表 II_第1张图片

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

ListNode *detectCycle(ListNode *head) {
     ListNode *slow = head, *fast = head;
     while (fast && fast->next) {
         slow = slow->next;
         fast = fast->next->next;
         if (slow == fast) {
             // 一个从相遇位置走,一个从头走,它们会在入口处相遇
             while (head != slow) {
                 slow = slow->next;
                 head = head->next;
             }
             return slow;
         }
     }
     return NULL;
}

你可能感兴趣的:(Data,Structure,and,Algorithm,C语言,刷题,leetcode,链表,linux,c语言,算法,数据结构)