My c++ accepted solution with O(n) time and O(1) space


  • 2
    B
    class Solution {
    public:
        ListNode *swapPairs(ListNode *head) {
            
            ListNode *p,*q,*pre;
            p=pre=head;
            while( p && p->next ) {
                
                if ( pre == head )
                    head = pre->next;
                q = p->next;
                pre->next = p->next;
                p->next = p->next->next;
                q->next = p;
                pre = p;
                p = p->next;
                
            }
            return head;
        }
    }

  • 0
    H

    is the variable pre useful?


Log in to reply
 

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