diff --git a/24- swap nodes in pairs.cpp b/24- swap nodes in pairs.cpp new file mode 100644 index 0000000..7921696 --- /dev/null +++ b/24- swap nodes in pairs.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + if (head == nullptr || + head->next == nullptr) { + return head; + } + + ListNode * prev = nullptr; + ListNode * curr = head; + ListNode * nxt = head->next; + + head = head->next; + + while (curr && nxt) { + if (prev) + prev->next = nxt; + curr->next = nxt->next; + nxt->next = curr; + prev = curr; + curr = curr->next; + if (curr) + nxt = curr->next; + } + + return head; + } +}; \ No newline at end of file