Share an iterative C++ solution with comments, can it be improved further?


  • 3
    E
    class Solution {
    public:
        ListNode *swapPairs(ListNode *head) {
            if (!head) return NULL;
            
            ListNode* p = head;
            ListNode* n = p->next;
            ListNode *s = NULL;
            while (n)
            {
               // 1->2->  become 2->1->
               p->next = n->next;
               n->next = p;
    
               // add link before n, ->2->1->
               if (!s) head = n;
               else    s->next = n;
               
               // move forward ->3->4->
               s = p;
               p = p->next;
               n = p ? p->next : NULL;
            }
            return head;
        }
    };

Log in to reply
 

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