Limited Time Offer:Up to 0% off Hello Interview Premium
Up to 0% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Linked List

Swap Nodes in Pairs

medium

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

Given a reference head of type ListNode that is the head of a singly linked list, write a function to 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.)

Example 1: input:

54321head

output:

45231head

Explanation: 5 and 4 are swapped, 3 and 2 are swapped, and 1 is left alone.

Example 2: input:

1234head

output:

2143head

Explanation: 1 and 2 are swapped, 3 and 4 are swapped.

Solution

Since we can't modify the values in the nodes, our function needs to swap the nodes by traversing the list and updating the next pointers of the nodes.
This question is an example of how using a dummy node simplifies a solution by removing the need for special logic for swapping the first two nodes in the list. To understand why, let's first look at how to swap a pair of nodes in a linked list.
Let's say we want to swap the pair of nodes first and second in the linked list below:
54321firstsecond
We need to perform 3 operations:
1). Since we need the node before first to point to second instead of first, we need a pointer prev which references the node before first. Then, we can update prev.next to point to second.
54321prevfirstsecond
2). We need to update first.next to point to second.next.
54321prevfirstsecond
3). Finally, we need to update second.next to point to first.
54321prevfirstsecond
Once that is complete, we can move to the next pair of nodes to swap.

Need for a Dummy Node

As we just saw, swapping a pair of nodes requires a pointer to node before the first node in the pair we want to swap. This is not a problem when we are swapping nodes in the middle of the list, but it is when we are swapping the first pair of nodes in the list because there is no node before head!
We fix this by introducing a dummy node that points to the head of the list. This guarantees that each node in the original list has a node before it, meaning we can swap all nodes in the list using the same logic.
Visualization
Python
Language
def swapPairs(head):
dummy = ListNode(0)
dummy.next = head
prev, first = dummy, head
while first and first.next:
second = first.next
# swap nodes
prev.next = second
first.next = second.next
second.next = first
prev = first
first = first.next
return dummy.next
54321

swap nodes in pairs

0 / 1

From there, we can initialize two pointers, prev and first. first will point to the first node in the pair we want to swap, and prev points to the node before first, which is the dummy node to start. We also initialize the pointer second to point to the node after first.
Visualization
Python
Language
def swapPairs(head):
dummy = ListNode(0)
dummy.next = head
prev, first = dummy, head
while first and first.next:
second = first.next
# swap nodes
prev.next = second
first.next = second.next
second.next = first
prev = first
first = first.next
return dummy.next
543210dummyprev

create dummy node

0 / 2

We then perform the same 3 operations we discussed earlier to swap the pair of nodes:
1). Update prev.next to point to second. 2). Update first.next to point to second.next. 3). Update second.next to point to first.
Visualization
Python
Language
def swapPairs(head):
dummy = ListNode(0)
dummy.next = head
prev, first = dummy, head
while first and first.next:
second = first.next
# swap nodes
prev.next = second
first.next = second.next
second.next = first
prev = first
first = first.next
return dummy.next
543210firstseconddummyprev

identify pair: 5 and 4

0 / 3

Now, with first and second swapped, we move prev and first to prepare for the next iteration. first now points to the node right before the next pair of nodes, so we update prev to point to first and first to point to first.next. After that, we update second to point to first.next, and our pointers are in the same state to perform the same 3 operations to swap the next pair of nodes.
Visualization
Python
Language
def swapPairs(head):
dummy = ListNode(0)
dummy.next = head
prev, first = dummy, head
while first and first.next:
second = first.next
# swap nodes
prev.next = second
first.next = second.next
second.next = first
prev = first
first = first.next
return dummy.next
543210firstseconddummyprev

second.next → 5

0 / 2

Termination

We can stop the loop when first is None, or when first.next is None. When there an even number of nodes in the list, first will be None when all pairs of nodes have been swapped. When there is an odd number of nodes, first.next will be None when first is at the last node in the list, which we can't swap.
After the loop terminates, we return dummy.next, which is the head of the list with all pairs of nodes swapped.
Visualization
Python
Language
def swapPairs(head):
dummy = ListNode(0)
dummy.next = head
prev, first = dummy, head
while first and first.next:
second = first.next
# swap nodes
prev.next = second
first.next = second.next
second.next = first
prev = first
first = first.next
return dummy.next
543210prevfirstdummy

no more pairs to swap

0 / 1

Implementation

Here's the complete dummy node approach that elegantly handles all edge cases:
Solution
Python
Language
def swapPairs(head):
# Create dummy node to simplify edge cases
dummy = ListNode(0)
dummy.next = head
prev = dummy
# Process pairs while both nodes exist
while prev.next and prev.next.next:
# Identify the two nodes to swap
first = prev.next
second = prev.next.next
# Perform the swap by adjusting pointers
prev.next = second # Link previous to second node
first.next = second.next # Link first to node after second
second.next = first # Link second to first (completing swap)
# Move prev to the end of swapped pair for next iteration
prev = first
return dummy.next # Return new head

Code

To construct the linked list that is used in the animation below, provide a list of integers nodes. Each integer in nodes is used as the value of a node in the linked list, and the order of the integers in nodes will be the order of the nodes in the linked list.
For example, if nodes = [1, 2, 3], the linked list will be 1 -> 2 -> 3.
Visualization
Python
Language
Try these examples:
def swapPairs(head):
dummy = ListNode(0)
dummy.next = head
prev, first = dummy, head
while first and first.next:
second = first.next
# swap nodes
prev.next = second
first.next = second.next
second.next = first
prev = first
first = first.next
return dummy.next
54321

swap nodes in pairs

0 / 16

Edge Cases

Empty List

When the list is empty, head is None. The while loop never runs, and we return dummy.next, which is equal to None.
Visualization
Python
Language
Try these examples:
def swapPairs(head):
dummy = ListNode(0)
dummy.next = head
prev, first = dummy, head
while first and first.next:
second = first.next
# swap nodes
prev.next = second
first.next = second.next
second.next = first
prev = first
first = first.next
return dummy.next

swap nodes in pairs

0 / 3

`head = []`

One Node

When there is only one node in the list, first is the only node in the list, and first.next is None. The while loop never runs, and we return dummy.next, which is head with the single node.
Visualization
Python
Language
def swapPairs(head):
dummy = ListNode(0)
dummy.next = head
prev, first = dummy, head
while first and first.next:
second = first.next
# swap nodes
prev.next = second
first.next = second.next
second.next = first
prev = first
first = first.next
return dummy.next
1

swap nodes in pairs

0 / 4

`head = [1]`

Two Nodes

When there are two nodes in the list, first is the first node, and second is the second node. The while loop runs once to swap the two nodes, after which fast is None so the loop terminates. We return dummy.next, which is the head of the list with the two nodes swapped.
Visualization
Python
Language
def swapPairs(head):
dummy = ListNode(0)
dummy.next = head
prev, first = dummy, head
while first and first.next:
second = first.next
# swap nodes
prev.next = second
first.next = second.next
second.next = first
prev = first
first = first.next
return dummy.next
12

swap nodes in pairs

0 / 10

`head = [1, 2]`
Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(N) where N is the number of nodes in the list. We visit each node in the list once, and perform the same number of operations at each node.

Space Complexity: O(1) We only use a constant amount of extra space to store the pointers prev, first, and second.

Mark as read

Next: Binary Search Overview

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Solution

Implementation

Code

Edge Cases

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsAnthropic SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress