Very short Iterative c++ Solution


  • 0
    F
    ListNode* swapPairs(ListNode* head) {
        ListNode dummy(0), *prev = &dummy, *curr = head, *tmp = NULL;
        
        while (curr && curr->next) {
            tmp = curr->next->next;
            prev->next = curr->next;
            prev->next->next = curr;
            prev = prev->next->next;
            curr = tmp;
        }
        
        prev->next = curr;
        return dummy.next;
    }

  • -1
    B
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            ListNode *ret = head;
            if(head == NULL) return ret;
            while(head&&head->next){
                int C= head->val;
                head->val = head->next->val;
                head->next->val=C;
                head = head->next;
                head = head->next;
            }
            return ret;
        }
    };

  • 0
    F

    The question mentions that you can't modify the value


Log in to reply
 

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