From 1da6f68efb0ae0ec8b2a4db5d0e4dacb630904f7 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Thu, 17 Feb 2022 00:09:06 +0800 Subject: [PATCH] add: 220216 --- 2202/220216.cpp | 59 +++++++++++++++++++++++++++++++++++++++++++++ 2202/CMakeLists.txt | 2 +- 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 2202/220216.cpp diff --git a/2202/220216.cpp b/2202/220216.cpp new file mode 100644 index 0000000..bf52e81 --- /dev/null +++ b/2202/220216.cpp @@ -0,0 +1,59 @@ +#include + +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode* next; + + explicit ListNode(int x = 0, ListNode* next = nullptr) : val(x), next(next) {} +}; + +ListNode* construct(int x) { + return new ListNode(x); +} + +template +ListNode* construct(int x, Ts... xs) { + return new ListNode(x, construct(xs...)); +} + +class Solution { +public: + static ListNode* swapPairs(ListNode* head) { + ListNode ret(0, head); + auto* ptr = &ret; + while (ptr) { + ListNode* ptrN = ptr->next; + if (!ptrN) + break; + + ListNode* ptrNN = ptrN->next; + if (!ptrNN) + break; + + // ptr --> ptrN --> ptrNN --> ptrNNN + ListNode* ptrNNN = ptrNN->next; + + // ptr is previous node + // swap ptrN and ptrNN. + ptrNN->next = ptrN; + ptr->next = ptrNN; + ptrN->next = ptrNNN; + + // ptr --> ptrNN --> ptrN --> ptrNNN + ptr = ptrN; + } + return ret.next; + } +}; + +int main() { + auto* head = construct(1, 2, 3, 4, 5, 6); + head = Solution::swapPairs(head); + for (auto* ptr = head; ptr; ptr = ptr->next) { + std::printf("%d ", ptr->val); + } + return 0; +} diff --git a/2202/CMakeLists.txt b/2202/CMakeLists.txt index 7d0ba3b..5b1fc4f 100644 --- a/2202/CMakeLists.txt +++ b/2202/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2202) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2202 220215.cpp) +ADD_EXECUTABLE(2202 220216.cpp)