369. Swap Nodes (Not Data) at Two Given Positions

MediumLinked ListLinked ListPointers

Given a singly linked list and two 0-based positions i and j, swap the two nodes at those positions by changing the node links (not just the values). If i equals j or a position is out of range, the list is unchanged. The list is given as an array; return the resulting array. Input: '[list], i, j'.

Input: '[list], i, j'.

Output: Array — the list after swapping.

Examples

Example 1
Input: [1,2,3,4,5], 0, 4
Output: [5,2,3,4,1]
Explanation: Head and tail swapped.
Example 2
Input: [1,2,3,4,5], 1, 3
Output: [1,4,3,2,5]
Explanation: Nodes 2 and 4 swapped.
Example 3
Input: [1], 0, 0
Output: [1]
Explanation: Same position, unchanged.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →