Search for a command to run...
You are given the head of a singly linked list containing integers. Your task is to reverse only those nodes whose values satisfy a given condition, while keeping the rest of the list unchanged.
The condition can vary (e.g., reverse only even numbers, only nodes greater than a given value k, etc.). The relative positions of nodes that do not satisfy the condition must remain the same, while the selected nodes should appear in reversed order among themselves.
Input Format:
The first line contains an integer n — the number of nodes in the linked list.
The second line contains n space-separated integers representing the linked list.
The third line contains a condition parameter (e.g., integer k or a rule like “even”).
Output Format:
Print the modified linked list after performing the conditional reversal.
Constraints:
1≤n≤1051 \leq n \leq 10^51≤n≤105
−109≤Node.value≤109-10^9 \leq Node.value \leq 10^9−109≤Node.value≤109
Example (Condition: Reverse Even Numbers): Input: 6 1 2 3 4 5 6
Output: 1 6 3 4 5 2
Explanation: Even elements = [2, 4, 6] → reversed → [6, 4, 2] Place them back in their original positions → Result: 1 6 3 4 5 2
Hint:
Traverse the list and store values that satisfy the condition.
Reverse those values.
Traverse again and replace only the matching nodes with values from the reversed list.
Example 1
2, 3, 5, 7, 8, 102, 3, 5, 7, 10, 8Example 2
1, 2, 3, 4, 6, 11, 2, 3, 6, 4, 1Example 3
1, 3, 5, 73, 1, 7, 52, 3, 5, 7, 8, 10
2, 3, 5, 7, 10, 8