11.Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.

Iterative Solution:-

Time Complexity: O(n)

class Solution
{
public:
    ListNode *swapPairs(ListNode *head)
    {
        
        if(head == NULL || head->next==NULL){return head;}

        ListNode *p = head->next;
        ListNode *q = head;

        while (p && q)
        {
            int temp = p->val;
            p->val = q->val;
            q->val = temp;
            if (p->next && p->next->next)
            {
                q = q->next->next;
                p = p->next->next;
            }
            else
            {
                break;
            }
        }

        return head;
    }
};

Recursive Solution:

class Solution
{
public:
    ListNode *swapPairs(ListNode *head)
    {
       
        if(head == NULL || head->next == NULL){
            return head;
        }
        
        int temp = head->val;
        head->val = head->next->val;
        head->next->val = temp;
        
        swapPairs(head->next->next);
        
        return head;
        
    }
};

Last updated