371. Pairwise Swap of Nodes

MediumLinked ListLinked ListRecursion

Given a singly linked list, swap every two adjacent nodes (by relinking, not by swapping values) and return the list. If the list has an odd number of nodes, the last node stays in place. The list is given as an array; return the resulting array.

Input: An array of node values.

Output: Array — the list after pairwise swaps.

Examples

Example 1
Input: [1,2,3,4,5]
Output: [2,1,4,3,5]
Explanation: Pairs swapped; last node unchanged.
Example 2
Input: [1,2,3,4]
Output: [2,1,4,3]
Explanation: Two pairs swapped.
Example 3
Input: [1]
Output: [1]
Explanation: Single node.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →