From 5672cedd3a9990b7face8443f98dd7d623ac4804 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Mon, 4 Apr 2022 10:30:08 +0800 Subject: [PATCH] add: 220404 [cpp] --- cpp/2204/220404.cpp | 29 +++++++++++++++++++++++++++++ cpp/2204/CMakeLists.txt | 2 +- 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 cpp/2204/220404.cpp diff --git a/cpp/2204/220404.cpp b/cpp/2204/220404.cpp new file mode 100644 index 0000000..7c7c5f6 --- /dev/null +++ b/cpp/2204/220404.cpp @@ -0,0 +1,29 @@ +#include + +/** + * 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; + } +}; diff --git a/cpp/2204/CMakeLists.txt b/cpp/2204/CMakeLists.txt index 452c84b..3b21d97 100644 --- a/cpp/2204/CMakeLists.txt +++ b/cpp/2204/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2204) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2204 220403-CN.cpp) +ADD_EXECUTABLE(2204 220404.cpp)