Swap Nodes in Pairs

样例

Given 1->2->3->4, you should return the list as2->1->4->3.

class Solution {
public:

    ListNode* swapPairs(ListNode* head) {
        if(head==NULL||head->next==NULL) return head;
        ListNode* dummy=new ListNode(-1);
        dummy->next=head;
        ListNode* pre=dummy;
        ListNode* cur=pre->next;
        while(cur&&cur->next){
            pre->next=cur->next;
            cur->next=pre->next->next;
            pre->next->next=cur;
            
            pre=pre->next->next;
            cur=pre->next;
        }
        return dummy->next;
    }
};


你可能感兴趣的:(Swap Nodes in Pairs)