LeetCode Linked List Cycle II

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* fast = head;
        ListNode* slow = head;
        while (step(fast, 2) && step(slow, 1)) {
            if (fast == slow) break;
        }
        if (fast == NULL) {
            return NULL;
        }
        ListNode* fake_end = slow;
        
        ListNode* h2 = fake_end->next;
        ListNode* h1 = head;
        
        ListNode* cur1 = h1;
        ListNode* cur2 = h2;
        
        int len1 = 0, len2 = 0;
        
        while (cur1 != fake_end) len1++, cur1 = cur1->next;
        while (cur2 != fake_end) len2++, cur2 = cur2->next;
        
        if (len1 == len2) {
            len1 = len2 = 0;
        } else if (len1 > len2) {
            len1 = len1 - len2;
            len2 = 0;
        } else {
            len1 = 0;
            len2 = len2 - len1;
        }
        
        step(h1, len1);
        step(h2, len2);
        
        while (h2 != h1 && step(h1, 1) && step(h2, 1));
        
        return h1;
    }
    
    bool step(ListNode* &cur, int n) {
        while (cur != NULL && n > 0) {
            n--;
            cur = cur->next;
        }
        return n == 0;
    }
};

求链表环和Y型链表交点的结合。

第二轮:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *detectCycle(ListNode *head) {
12         if (head == NULL) {
13             return NULL;
14         }
15         
16         ListNode fakeHead(0);
17         fakeHead.next = head;
18         
19         ListNode* fast = fakeHead.next->next;
20         ListNode* slow = fakeHead.next;
21         
22         while (fast != NULL && fast->next != NULL) {
23             if (fast == slow) {
24                 break;
25             }
26             fast = fast->next->next;
27             slow = slow->next;
28         }
29         if (fast == NULL || fast->next == NULL) return NULL;
30         
31         fast = &fakeHead;
32         while (fast != slow) {
33             fast = fast->next;
34             slow = slow->next;
35         }
36         return fast;
37     }
38 };
原文地址:https://www.cnblogs.com/lailailai/p/3800013.html