Solution for LeetCode LeetCode: Swap nodes in Pairs
Leetcode Problem: Swap Nodes in Pairs
https://leetcode.com/problems/swapnodesinpairs/
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:

Explanation and solution
To solve this question, you need to master basic operation skills for link list, and how to swap two nodes.
The time complexity is $O(N)$.
Naive solution: Traversal link list and reverse it on fly
Use a dummy node
will simplify the operations.
The result is:

Recursive solution
The code will be cleaner if we use recursive strategy, but it will be slower in time performance.

Join my Email List for more insights, It's Free!😋