add: 220216

This commit is contained in:
Lam Haoyin 2022-02-17 00:09:06 +08:00
parent 491c957eee
commit 1da6f68efb
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 60 additions and 1 deletions

59
2202/220216.cpp Normal file
View File

@ -0,0 +1,59 @@
#include <iostream>
/**
* 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<typename... Ts>
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;
}

View File

@ -3,4 +3,4 @@ PROJECT(2202)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2202 220215.cpp) ADD_EXECUTABLE(2202 220216.cpp)