#C11516. Swap Nodes in a Linked List
Swap Nodes in a Linked List
Swap Nodes in a Linked List
You are given a singly linked list and two integer values x and y. Your task is to swap the nodes containing these values in the linked list. If one or both values are not present, the linked list should remain unchanged.
Note: You are required to swap the nodes themselves, not just the values in the nodes. The structure of the linked list must be maintained.
Example:
Input: 1 2 3 4 5 (linked list), x = 2, y = 4 Output: 1 4 3 2 5
The problem may involve various scenarios, including swapping adjacent nodes, swapping head or tail nodes, and handling empty or single element linked lists.
In mathematical view, let \(L = [l_1, l_2, \ldots, l_n]\) be the list, and the operation swaps positions of \(l_i\) and \(l_j\) if \(l_i=x\) and \(l_j=y\) (or vice versa), i.e.:
[
L^* = [l_1, \ldots, l_{i-1}, l_j, l_{i+1}, \ldots, l_{j-1}, l_i, l_{j+1}, \ldots, l_n]
]
inputFormat
The input is read from standard input (stdin) and consists of three parts:
- An integer
n
representing the number of nodes in the linked list. - A sequence of
n
space-separated integers, which are the values of the nodes in order. - Two space-separated integers,
x
andy
, representing the values of the nodes to be swapped.
For example:
5 1 2 3 4 5 2 4
outputFormat
Output the modified linked list as a sequence of integers separated by a single space, printed to standard output (stdout). If no swap occurs, output the original linked list.
For example:
1 4 3 2 5## sample
5
1 2 3 4 5
2 4
1 4 3 2 5