Created
July 18, 2022 11:57
-
-
Save icameling/b5e3003e847a3bed015a78ce3bc21dcf to your computer and use it in GitHub Desktop.
#链表 #环形链表 II
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
if (head == NULL) return NULL; | |
ListNode* slow = head; | |
ListNode* fast = head; | |
while (fast != NULL && fast->next != NULL) { | |
slow = slow->next; | |
fast = fast->next->next; | |
if (slow == fast) { | |
ListNode* tmp = head; | |
while (tmp != fast) { | |
tmp = tmp->next; | |
fast = fast->next; | |
} | |
return tmp; | |
} | |
} | |
return NULL; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment