340. Swap Data of Two Nodes without Swapping Pointers

EasyLinked ListLinked ListSwapPointer Manipulation

Given the head of a singly linked list and two 1-based positions pos1 and pos2, swap the values of the nodes at those positions (swap node data, not pointers). Return the head.

It is guaranteed that pos1 and pos2 are valid positions (1 <= pos <= n).

Input: Head of a singly linked list and two 1-based positions pos1, pos2.

Output: Head of the list with values at pos1 and pos2 swapped.

Examples

Example 1
Input: [1,2,3,4,5], 2, 4
Output: [1,4,3,2,5]
Explanation: Node at pos2(val=4) and node at pos4(val=2) swap values.
Example 2
Input: [1,2,3,4,5], 1, 5
Output: [5,2,3,4,1]
Explanation: Head(1) and tail(5) swap values.
Example 3
Input: [1,2,3], 2, 2
Output: [1,2,3]
Explanation: Same position, no change.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →