C++ 3 lines Solution (Easy to Understand,for loop)


  • 0
    K

    class Solution {
    public:
    ListNode
    swapPairs(ListNode
    head) {
    for(ListNode i=head;i!=NULL&&i->next!=NULL;i=i->next->next)
    swap(i->val,i->next->val);
    return head;
    }

    };


  • 1
    M

    @karan.vas1994 In the problem description it says: "You may not modify the values in the list" so I think this solution is not valid technically.


  • 0
    K

    Thanks for pointing out ,

    ListNode* swapPairs(ListNode* head) {
    for(ListNode *i=head,*j=i->next;i!=NULL&&i->next!=NULL;i=i->next,j=i->next){

            i->next=i->next->next;
            j->next=i;
            //swap(i->val,i->next->val);
        }
        return head;
    }

Log in to reply
 

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