My C++ solution with constant space


  • 1
    F

    class Solution {
    public:
    ListNode* swapPairs(ListNode* head) {

        if(head == NULL || head->next == NULL)
            return head;
    
        ListNode *start = head->next;
        ListNode *first,*second,*lastpairs,*Nextpair;
        int count = 0;
        while(head != NULL && head->next != NULL)
        {
            first = head;
            second = head->next;
            Nextpair = head->next->next;
            second->next = head;
            first->next  = Nextpair;
            if(count == 0)
            {
                count = 1;
            }
            else
                lastpairs->next = second;
    
            head = Nextpair;
            lastpairs = first;
        }
        return start;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.