LeetCode Day21 Swap Nodes in Pairs

法一:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head==NULL || head->next==NULL) return head;
        ListNode *pb=head,*pf=head->next,*tmp;
        head=pf;
        while(1){
            tmp=pb;
            pb->next=pf->next;
            pf->next=pb;
            pb=pb->next;
            if(!pb || !pb->next) break;
            else{
                pf=pb->next;
                tmp->next=pf;
            }
        }
        return head;
    }
};

法二:迭代

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head==NULL || head->next==NULL) return head;
        ListNode *t=head->next;
        head->next=swapPairs(head->next->next);
        t->next=head;
        return t;
    }
};

法三:
建立一个节点pre,用来存放上一次的尾部

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *dummy=new ListNode(-1),*pre=dummy;
        dummy->next=head;
        while(pre->next && pre->next->next){
            ListNode *t=pre->next->next;
            pre->next->next=t->next;
            t->next=pre->next;
            pre->next=t;
            pre=t->next;
        }
        return dummy->next;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41394379/article/details/83214104