Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)


Test Cases

Example 1:

Input: head = [1,2,3,4]
Output: [2,1,4,3]
Explanation:
1->2->3->4      ->     2->1->4->3

Example 2:

Input: head = []
Output: []

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* swapPairs(struct ListNode* head){
    if (head == NULL || head->next == NULL) return head;
    struct ListNode *l1 = head, *l2 = head->next;
    l1->next = l2->next;
    l2->next = l1;
    l1->next = swapPairs(l1->next);
    return l2;
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == NULL || head->next == NULL) return head;
        ListNode *l1 = head, *l2 = head->next;
        l1->next = l2->next;
        l2->next = l1;
        l1->next = swapPairs(l1->next);
        return l2;
    }
};
package swap_nodes_in_pairs

type ListNode struct {
	Val int
	Next *ListNode
}

func swapPairs(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	l1 := head
	l2 := head.Next
	l1.Next = l2.Next
	l2.Next = l1
	l1.Next = swapPairs(l1.Next)
	return l2
}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode l1 = head, l2 = head.next;
        l1.next = l2.next;
        l2.next = l1;
        l1.next = swapPairs(l1.next);
        return l2;
    }
}
from typing import Optional


# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head
        l1, l2 = head, head.next
        l1.next = l2.next
        l2.next = l1
        l1.next = self.swapPairs(l1.next)
        return l2
Time Complexity: O(n)
Space Complexity: O(1)