diff --git a/solution/142.Linked List Cycle II/README.md b/solution/142.Linked List Cycle II/README.md index 4a76e66bc3b64..b122836447164 100644 --- a/solution/142.Linked List Cycle II/README.md +++ b/solution/142.Linked List Cycle II/README.md @@ -67,4 +67,32 @@ public class Solution { } } +``` + +#### CPP + +```C++ +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + if(head == NULL)return NULL; + ListNode *fast = head; + ListNode *slow = head; + while(fast != NULL && fast->next != NULL){ + fast = fast->next->next; + slow = slow->next; + + if(fast == slow){ + slow = head; + while(slow != fast){ + fast = fast->next; + slow = slow->next; + } + return fast; + } + } + return NULL;//无环 + } +}; + ``` \ No newline at end of file diff --git a/solution/142.Linked List Cycle II/Solution.cpp b/solution/142.Linked List Cycle II/Solution.cpp new file mode 100644 index 0000000000000..c64fa506f64c9 --- /dev/null +++ b/solution/142.Linked List Cycle II/Solution.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + if(head == NULL)return NULL; + ListNode *fast = head; + ListNode *slow = head; + while(fast != NULL && fast->next != NULL){ + fast = fast->next->next; + slow = slow->next; + + if(fast == slow){ + slow = head; + while(slow != fast){ + fast = fast->next; + slow = slow->next; + } + return fast; + } + } + return NULL;//无环 + } +};