swap.cpp (1215B)
1 #include <iostream> 2 /** 3 * Definition for singly-linked list. 4 * struct ListNode { 5 * int val; 6 * ListNode *next; 7 * ListNode() : val(0), next(nullptr) {} 8 * ListNode(int x) : val(x), next(nullptr) {} 9 * ListNode(int x, ListNode *next) : val(x), next(next) {} 10 * }; 11 */ 12 13 // two pointers 14 // first one stays on the prior (second pair) 15 // second one goes two ahead to swap 16 // swap 17 // increment 18 19 class Solution { 20 public: 21 ListNode* swapPairs(ListNode* head) { 22 23 ListNode* original = head; 24 ListNode* prior = nullptr; 25 26 bool first = true; 27 28 while (head != nullptr && head->next != nullptr){ 29 ListNode* newFirst = swap(prior, head, head->next, head->next->next); 30 head = newFirst->next->next; 31 if (first == true){ 32 first = false; 33 original = newFirst; 34 } 35 prior = newFirst->next; 36 } 37 38 return original; 39 } 40 ListNode* swap(ListNode* prior, ListNode* first, ListNode* second, ListNode* third){ 41 42 second->next = first; 43 first->next = third; 44 if(prior != nullptr){ 45 prior->next = second; 46 } 47 return second; 48 } 49 };