add: 220404 [cpp]

This commit is contained in:
Lam Haoyin 2022-04-04 10:30:08 +08:00
parent 5ad6c8b296
commit 5672cedd3a
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 30 additions and 1 deletions

29
cpp/2204/220404.cpp Normal file
View File

@ -0,0 +1,29 @@
#include <algorithm>
/**
* 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 {
public:
static ListNode* swapNodes(ListNode* head, int k) {
if (!head || !head->next) return head;
auto* fast = head;
for (int i = 1; i < k; ++i)
fast = fast->next;
auto* slow = head;
auto* S1 = fast;
while (fast->next) {
fast = fast->next;
slow = slow->next;
}
std::swap(slow->val, S1->val);
return head;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2204)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2204 220403-CN.cpp)
ADD_EXECUTABLE(2204 220404.cpp)