Linked List in Zig-Zag fashion

Linked List in Zig-Zag fashion

Given a Linked list, rearrange it such that converted list should be of the from a < b > c < d > e < f .. where a, b, c are consecutive data node of linked list and such that the order of linked list is sustained.

For example:
In 11 15 20 5 10 we consider only 11 20 5 15 10 because it satisfies the above condition and the order of linked list. 5 20 11 15 10 is not considered as it does not follow the order of linked list.

Algorithm

  • If list is empty or list has only one child then return
  • Set mode = zig
  • Iterate till node.next != null
    • if (mode == zig and node.data > node.next.data) then swap node.data with node.next.data
    • if (mode == zag and node.data < node.next.data) then swap node.data with node.next.data
    • set mode = (mode== zig) ? zag : zig

Latest Source Code:
Github: ListZigZagReorder.java


Output:

11 15 20 5 10 
11 20 5 15 10 
Author: Hrishikesh Mishra