Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Swap Nodes in Pairs
MEDIUM
40 mins
15 upvotes
Linked List
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Linked List
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Swap Nodes in Pairs

Contributed by
Amandeep Kaur
Medium
yellow-spark
0/80
Avg time to solve 40 mins
Success Rate 60 %
Share
15 upvotes

Problem Statement

You are given a singly linked list of integers.

Your task is to swap every two adjacent nodes, and return the head of the modified, linked list.

For Example:

We have a linked list 1->2->3->4->5->6->7 and so on. You are supposed to swap pairs of a linked list like swap (1,2), (3,4), (5,6), and so on.
Note:
1. You may not modify the data in the list’s nodes; only nodes themselves may be changed. Because imagine a case where a node contains many fields, so there will be too much unnecessary swap.

2. If a pair of a node does not exist, then leave the node as it is.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1:
11 21 13 14 15 -1
Sample Output 1:
21 11 14 13 15 -1
Explanation of the Sample Input1:
Swap 11 with 21 then swap 13 with 14 and 15 has no pair so leave that node as it is.
Sample Input 2:
-13 14 -21 18 -20 30 -1
Sample Output 2:
14 -13 18 -21 30 -20 -1
Explanation of the Sample Input 2:
Swap -13 with 14 then swap -21 with 18 and then swap -20 to with 30.
Reset Code
Full screen
Auto
copy-code
Console