Please suggest what is wrong with the logic I used in swap nodes pairwise problem given below


  • 0
    H
    class Solution {
    public:
    ListNode *swapPairs(ListNode *head) {
        ListNode *temp=head;
        while(temp!=NULL && temp->next!=NULL) {
            swap(&temp->val,&temp->next->val);
            temp=temp->next->next;
        }
        return temp;
    }
    void swap(int *a,int *b) {
      int c=*a;
      *a=*b;
      *b=c;
        
    }
    

    };


  • 1
    S

    Swap function should always pass reference or pointer, instead of value.

    // passing reference
    void swap(int &a,int &b) {
      int c=a;
      a=b;
      b=c;
    
    }
    
    swap(a, b);
    
    // passing pointer
    void swap(int *a,int *b) {
      int c=*a;
      *a=*b;
      *b=c;
    
    }
    swap(&a, &b);

  • 0
    H

    Hi Shangrila,

    I tried both by reference and by value, but got wrong answer in both the case.
    Do you have any other suggestion as well?


  • 1
    S

    The problem is not about the swap function. It is fine as long as you pass the parameters by reference or pass the pointers. The problem is, you should return 'head' instead of 'temp', which would point to the end ('null') of the linked list by the end of the function.


  • 0
    H

    Thanks, :) it worked out


Log in to reply
 

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