Skip to content

Instantly share code, notes, and snippets.

@icameling
Created July 18, 2022 11:57
Show Gist options
  • Save icameling/b5e3003e847a3bed015a78ce3bc21dcf to your computer and use it in GitHub Desktop.
Save icameling/b5e3003e847a3bed015a78ce3bc21dcf to your computer and use it in GitHub Desktop.
#链表 #环形链表 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) {
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