Given the head of a linked list, rearrange the nodes to form a zig-zag pattern: a ≤ b ≥ c ≤ d ≥ e ≤ f ... It means the first pair (a, b) is increasing, second pair (b, c) is decreasing, third pair (c, d) is increasing and so on in the modified linked list.
Only swapping of adjacent nodes is allowed.
You may swap also already swapped adjacent but cannot swap two nodes which are not adjacent.
For example, for the linked list: 11 -> 15 -> 20 -> 5 -> 10
11 -> 20 -> 5 -> 15 -> 10 is valid, while
5 -> 20 -> 11 -> 15 -> 10 is invalid because it changes the relative order of nodes.
Return the head of the modified zig-zag linked list.
[Naive Approach] Repeated Traversal using Adjacent Swapping - O(n^2) Time O(1) Space
The idea is to repeatedly traverse the linked list and maintain the zig-zag pattern using a flag. If the current adjacent pair does not satisfy the required relation (≤ or ≥), swap their data values. Continue this process until no swaps are needed in a complete traversal.
Output
true
Time Complexity: O(n^2) Space Complexity: O(1)
[Expected Approach] Using Single Traversal using Flag - O(n) Time O(1) Space
The idea is to traverse the linked list once using a flag to maintain the zig-zag pattern. If the current pair does not satisfy the required relation (≤ or ≥), swap their data values and flip the flag for the next pair.
Let us understand with an example: Input: head: 11 -> 15 -> 20 -> 5 -> 10 Compare 11 and 15 (<= needed), condition satisfied.