nikunjsoni

24

Mar 21st, 2021
70
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12. public:
  13.     ListNode* swapPairs(ListNode* head) {
  14.         if(!head) return head;
  15.         ListNode *dummy = new ListNode(0, head);
  16.         ListNode *curr, *next, *prev;
  17.         curr = head; next = curr->next; prev = dummy;
  18.         while(next){
  19.             curr->next = next->next;
  20.             next->next = curr;
  21.             prev->next = next;
  22.             prev = curr;
  23.             curr = curr->next;
  24.             next = (curr) ? curr->next : NULL;
  25.         }
  26.         return dummy->next;
  27.     }
  28. };
RAW Paste Data