From 138d872a73449fdd4c63f7291fed23752eb7eda1 Mon Sep 17 00:00:00 2001 From: Anusha Kulkarni <88369729+hi-anusha@users.noreply.github.com> Date: Fri, 7 Oct 2022 11:03:53 +0530 Subject: [PATCH] this commit fixes #136 Added c++ solution --- 24- swap nodes in pairs.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 24- swap nodes in pairs.cpp 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