Solution in c


  • -1
    B
    struct ListNode* swapPairs(struct ListNode* head) {
        struct ListNode* temp1,*temp2,*prev;
        if(head==NULL)
        return head;
        temp1=head;
        temp2=head->next;
        if(temp1!=NULL&&temp2!=NULL){
            temp1->next=temp2->next;
            temp2->next=temp1;
            head=temp2;
            prev=temp1;
            temp1=temp1->next;
            if(temp1)
            temp2=temp1->next;
            
        }
        while(temp1!=NULL&&temp2!=NULL){
            prev->next=temp2;
            temp1->next=temp2->next;
            temp2->next=temp1;
            prev=temp1;
            temp1=temp1->next;
            if(temp1)
            temp2=temp1->next;
        }
        return head;
    }
    

  • 0

    @bharadwaj5 Could you please format your code properly by surround your code with 3 backticks?

    Like this:

    ```
    Your code here
    ```

  • 0

    @bharadwaj5 I helped you out this time, but try to use three backquotes to format your code properly next time.


  • 0

    Your code is rather a mess here. Check this

    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) 
        {
            ListNode newHead(0), *pre, *cur = head;
            pre = &newHead;
            newHead.next = head;
            while(cur && cur->next)
            {
                pre->next = cur->next;
                cur->next = cur->next->next;
                pre->next->next = cur;
                cur = cur->next;
                pre = pre->next->next;
            }
            return newHead.next;
        }
    };
    

Log in to reply
 

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