# 24. Swap Nodes in Pairs Difficulty: Medium ## Solution ```cpp= /** *** Author: R-CO *** E-mail: daniel1820kobe@gmail.com *** Date: 2020-09-01 **/ #include <cstdlib> #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode* odd = nullptr; ListNode* even = nullptr; ListNode* pre_even = nullptr; ListNode* ptr = head; size_t count = 0; while (ptr != nullptr) { if ((++count & 0x1) == 0) { even = ptr; ptr = ptr->next; even->next = odd; odd->next = ptr; if (pre_even != nullptr) { pre_even->next = even; } pre_even = odd; if (count == 2) { head = even; } } else { odd = ptr; ptr = ptr->next; } } return head; } }; void DisplayList(ListNode* head) { while (head != nullptr) { cout << head->val << " "; head = head->next; } } void ReleaseList(ListNode* head) { while (head != nullptr) { auto ptr = head; head = head->next; delete ptr; } } int main(int argc, char* argv[]) { /* 1->2->3->4->5->6 2->1->4->3->6->5 */ auto head = new ListNode(1); auto ptr = head; for (int i = 2; i <= 6; ++i) { ptr->next = new ListNode(i); ptr = ptr->next; } DisplayList(head); cout << endl; Solution solution; head = solution.swapPairs(head); DisplayList(head); cout << endl; ReleaseList(head); return EXIT_SUCCESS; } ``` ## Result Success Details Runtime: 4 ms, faster than 59.11% of C++ online submissions for Swap Nodes in Pairs. Memory Usage: 7.4 MB, less than 85.95% of C++ online submissions for Swap Nodes in Pairs. ###### tags: `LeetCode-Medium` `C++`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up