Swap List Nodes in pairs

TopicDifficultyCompanies
Linked List
EASY
Amazon
Microsoft

You are given the head of a linked list, write a program to swap each pair of adjacent nodes.

Problem Note

  • Linked List can be of even or odd size.
  • You shouldn't modify the values of nodes, rather swap the nodes itself

Example 1

Input: 10->20->30->40
Output: 20->10->40->30
Explanation: The pair of adjacent nodes having value 10 and 20 are swapped. Similarly, pair of adjacent nodes having value 30 and 40 are swapped.

Example 2

Input: 80->20->5->9->2
Output: 20->80->9->5->2
Explanation: The adjacent nodes are swapped till the last node having value 2. As there is no next node to it, it remains at the same position.

Example 3

Input: 1->2
Output: 2->1
Explanation: There is only pair of adjacent nodes and they are swapped together.

Code Editor

Practice and Learn

Best way to learn is through solving real problems. Practice this problem in this code editor.