Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Solution: Swap Nodes in Pairs
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

Given a singly linked list, swap every two adjacent nodes and return the head of the modified list.

If the total number of nodes in the list is odd, the last node remains in place. Every node in the linked list contains a single integer value.

Examples

  1. Input: [1, 2, 3, 4]
    Output: [2, 1, 4, 3]
    Justification: Pairs (1,2) and (3,4) are swapped.

  2. Input: [7, 8, 9, 10, 11]
    Output: [8, 7, 10, 9, 11]
    Justification: Pairs (7,8) and (9,10) are swapped. 11 remains in its place as it has no adjacent node to swap with.

3

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible