add: 211228

This commit is contained in:
Lam Haoyin 2021-12-28 08:48:45 +08:00
parent da919308b6
commit 73fda72214
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 39 additions and 1 deletions

38
2112/211228.cpp Normal file
View File

@ -0,0 +1,38 @@
#include <cstdio>
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
explicit ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
~ListNode() { delete this->next; }
};
class Solution {
public:
static ListNode* middleNode(const ListNode* const head) {
const auto* fast = head;
const auto* slow = fast;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
return const_cast<ListNode*>(slow);
}
};
int main() {
auto* H = new ListNode(1);
auto* ptr = H;
for (int i = 2; i <= 6; ++i) {
ptr->next = new ListNode(i);
ptr = ptr->next;
}
for (const auto* M = Solution::middleNode(H); M; M = M->next)
std::printf("%d\n", M->val);
delete H;
}

View File

@ -3,4 +3,4 @@ PROJECT(2112)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2112 211227.cpp)
ADD_EXECUTABLE(2112 211228.cpp)