[LeetCode] Swap Nodes in Pairs

 

class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        if (head == NULL || head->next == NULL) return head;
        ListNode* newhead = head->next;
        ListNode* prev = NULL, *cur1 = head, *cur2 = head->next;;
        prev = cur1;
        cur1->next = cur2->next;
        cur2->next = cur1;
        while (prev->next != NULL && prev->next->next != NULL) {
            cur1 = prev->next;
            cur2 = cur1->next;
            
            prev->next = cur2;
            cur1->next = cur2->next;
            cur2->next = cur1;
            prev = cur1;
        }
        return newhead;
    }
};

 

猜你喜欢

转载自cozilla.iteye.com/blog/1869832