Input: 10->15->12->13->20->14, x = 10, y = 20 Output: 20->15->12->13->10->14
Possible cases to handle:
When swapping 2 nodes, x and y, in a linked list, there are a few cases that can arise:
x and y are adjacent to each other, and
One of x or y is the head node of the list.
None of x or y is either a head node or a tail node.
x and y are not adjacent to each other, and:
One of x or y is the head node of the list.
None of x or y is either a head node or a tail node.
x or y donβt even exist in the linked list.
Therefore, our solution must handle all these cases.
[Naive Approach] By Keeping Track of Previous Node - O(n) Time and O(1) Space:
The idea is to first search x and y nodes in the given linked list. If any of them is not present, then return. While searching for x and y, keep track of current and previous pointers. First change next of previous pointers, then change next of current pointers.
Below is the diagram of the case where either Node X or Node Y is the head node of the list.