Swap Nodes in Pairs - C++


  • 0
    V
    /**
     * 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) 
        {
            if(head != NULL && head->next != NULL)
            {
                ListNode *temp = head->next;
                ListNode *next = temp->next;
                temp->next = head;
                head->next = swapPairs(next);
                head = temp;
            }
            
            return head;
        }
    };
    

Log in to reply
 

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