Swap Nodes in Pairs
To swap every two adjacent nodes in a linked list without modifying the values in the list’s nodes, you can follow the following steps:
- Create a dummy node and link it to the head of the list.
- Use a pointer (
prev
) to keep track of the previous node in the swapped list. - Use two pointers (
first
andsecond
) to refer to the two nodes that need to be swapped. - Adjust the links to perform the swap.
- Update the
prev
pointer to the last node in the swapped pair. - Continue this process for every pair of nodes in the list.
Here’s the code that implements this logic:
|
|
This code snippet swaps adjacent pairs in the linked list, taking care of edge cases when there are no nodes or only one node in the list. The time complexity of this solution is ( O(n) ), where ( n ) is the number of nodes in the list, and the space complexity is ( O(1) ), as we only used a constant amount of extra space.