add: 220404 [cpp]
This commit is contained in:
parent
5ad6c8b296
commit
5672cedd3a
|
|
@ -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;
|
||||
}
|
||||
};
|
||||
|
|
@ -3,4 +3,4 @@ PROJECT(2204)
|
|||
|
||||
SET(CMAKE_CXX_STANDARD 23)
|
||||
|
||||
ADD_EXECUTABLE(2204 220403-CN.cpp)
|
||||
ADD_EXECUTABLE(2204 220404.cpp)
|
||||
|
|
|
|||
Loading…
Reference in New Issue