leetCode_swap_pairs Posted on 2020-11-21 | backgroundLeetCode24: swap pairs intuitive sol123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 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) {} };#include <iostream>class Solution {public: ListNode* swapPairs(ListNode* head) { ListNode *dummy = new ListNode(-1); ListNode *prev = dummy ; prev->next = head ; ListNode *p1=head, *p2=p1->next, *p3=p2->next, *p4=p3->next, *pn, *tmp ; if(p1 == nullptr) { return nullptr ; }else if(p2 == nullptr){ return p1 ; }else if(p3 == nullptr) { p2->next = p1 ; p1->next = nullptr ; head = p2 ; return head ; }else if(p4 == nullptr) { head->next = p2 ; p2->next = p1 ; p1 ->next = p3; return head ; } for(p1=head, p2=p1->next, p3=p2->next, p4=p3->next ; p4 && p3 && p2 && p1; prev=p3, p1=prev->next, p2=p1->next, p3=p2->next, p4=p3->next ){ pn = p4->next ; p2->next = p1 ; p4->next = p3 ; p1->next = p4; p3->next = pn ; prev->next = p2 ; if (pn == nullptr) { break; }else if(pn->next == nullptr) { break; }else if (pn->next->next == nullptr) { break; }else if(pn->next->next->next == nullptr) { break; }} if(pn == nullptr || pn->next == nullptr){ return prev->next; } if(pn->next->next == nullptr ) { tmp = pn->next ; prev->next = pn->next ; tmp->next = pn ; pn->next = nullptr; }else if(pn->next->next->next == nullptr){ tmp = pn->next ; ListNode *last = tmp->next ; prev->next = tmp ; pn->next = last ; } return prev->next; }};int main(){ ListNode *head = new ListNode(1); ListNode *sec = new ListNode(2); ListNode *thd = new ListNode(3); ListNode *fth = new ListNode(4); head->next = sec ; sec->next = thd ; thd->next = fth ; Solution *sol = new Solution(); ListNode *res = sol->swapPairs(head) ; std::cout << res->val << ', ' << res->next->val << ', ' << res->next->next->val << std::endl; return 0;}