add: 220308 [cpp]
This commit is contained in:
parent
d21d923526
commit
ea732597d4
|
|
@ -0,0 +1,54 @@
|
|||
#include <iostream>
|
||||
#include <cassert>
|
||||
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
*/
|
||||
struct ListNode {
|
||||
int val;
|
||||
ListNode* next;
|
||||
explicit ListNode(int x, ListNode* n = nullptr) : val(x), next(n) {}
|
||||
~ListNode() { delete this->next; this->next = nullptr; }
|
||||
};
|
||||
|
||||
class Solution {
|
||||
private:
|
||||
/**
|
||||
* Solution for problem # 142
|
||||
* Refer: 220119.cpp
|
||||
* @param head Head of linked "list"
|
||||
* @return Pointer to where the cycle begins
|
||||
*/
|
||||
static ListNode* detectCycle(const ListNode* head) {
|
||||
if (!(head && head->next))
|
||||
return nullptr;
|
||||
const auto* fast = head->next->next;
|
||||
const auto* slow = head->next;
|
||||
for (; fast && fast->next && fast != slow; ) {
|
||||
fast = fast->next->next;
|
||||
slow = slow->next;
|
||||
}
|
||||
if (!(fast && fast->next))
|
||||
return nullptr;
|
||||
assert(fast == slow);
|
||||
int cycleLength = 1;
|
||||
for (fast = fast->next; fast != slow; ++cycleLength, (fast = fast->next));
|
||||
fast = slow = head;
|
||||
for (int i = 0; i < cycleLength; ++i)
|
||||
fast = fast->next;
|
||||
if (fast == slow) {
|
||||
for (int i = 1; i < cycleLength; ++i)
|
||||
fast = fast->next;
|
||||
} else {
|
||||
while (fast->next != slow->next) {
|
||||
fast = fast->next;
|
||||
slow = slow->next;
|
||||
}
|
||||
}
|
||||
return const_cast<ListNode*>(fast->next);
|
||||
}
|
||||
public:
|
||||
static bool hasCycle(ListNode *head) {
|
||||
return detectCycle(head) != nullptr;
|
||||
}
|
||||
};
|
||||
|
|
@ -3,4 +3,4 @@ PROJECT(2203)
|
|||
|
||||
SET(CMAKE_CXX_STANDARD 23)
|
||||
|
||||
ADD_EXECUTABLE(2203 220307-CN.cpp)
|
||||
ADD_EXECUTABLE(2203 220308.cpp)
|
||||
|
|
|
|||
Loading…
Reference in New Issue