C++ solution with comment


  • 0
    L

    Time O(n/2) Space O(1)

    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            // temp variable for swapping value
            int temp;
            // store head location
            ListNode* result = head;
            while(head) {
                temp = head->val;
                // if head has next swap current val and next val
                // else is the safety for odd length of the linkedlist
                if (head->next) {
                    head->val = head->next->val;
                    head->next->val = temp;
                    // skip after swap, so you skip in pair
                    head = head->next->next;
                } else {
                     head = head->next;
                }
            }
            return result;
        }
    };
    

Log in to reply
 

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