VOOZH about

URL: https://www.geeksforgeeks.org/dsa/linked-list-in-zig-zag-fashion/

⇱ Rearrange a Linked List in Zig-Zag fashion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rearrange a Linked List in Zig-Zag fashion

Last Updated : 28 May, 2026

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.

Examples:

Input: head: 1 -> 2 -> 3 -> 4

👁 1

Output: 1->3->2->4

👁 2

Explanation: In the given linked list, after arranging them as 1 ≤ 3 ≥ 2 ≤ 4 in the pattern as asked above.

Input: head: 11 -> 15 -> 20 -> 5 -> 10

👁 3

Output: 11->20->5->15->10

👁 4

Explanation: In the given linked list, after arranging them as 11 ≤ 20 ≥ 5 ≤ 15 ≥ 10 in the pattern as asked above.

[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.

  • Compare 15 and 20 (>= needed), swap → 11 -> 20 -> 15 -> 5 -> 10
  • Compare 15 and 5 (<= needed), swap → 11 -> 20 -> 5 -> 15 -> 10
  • Compare 15 and 10 (>= needed), condition satisfied.

Final List: 11 -> 20 -> 5 -> 15 -> 10


Output
true

Time Complexity: O(n)
Space Complexity: O(1)

Comment
Article Tags: