Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Swap Nodes in Pairs

Medium Acceptance 65% Points 30

You are given the head of a singly linked list. Your task is to swap every two adjacent nodes without modifying the values stored in the nodes and return the head of the modified list. If the linked list contains an odd number of nodes, the last node remains unchanged.

Examples
Example 1

Example 1

Input: head = [1,2,3,4]

Output: [2,1,4,3]

Explanation: Every pair of adjacent nodes is swapped.

Example 2

Example 2

Input: head = [1,2,3]

Output: [2,1,3]

Explanation: The first pair is swapped, while the last node remains unchanged.

Example 3

Example 3

Input: head = [10]

Output: [10]

Explanation: A single-node linked list remains unchanged.

Constraints
  • 1 = Number of nodes = 105
  • -10? = Node.data = 10
Topics
Linked List
Companies
Amazon
Added 26 Jul 2026 65% acceptance
Ln 1, Col 1Sign in to save your code
1 2 3 4
2 1 4 3