Given a linked list, rearrange it such that converted list should be of the form a < b > c < d > e < f .. where a, b, c.. are consecutive data node of linked list. Note that it is not allowed to swap data.
Input: 1->2->3->4 Output: 1->3->2->4 Input: 11->15->20->5->10 Output: 11->20->5->15->10
A solution that converts given list into zigzag form is discussed in previous post. The solution discussed performs conversion by swapping data of nodes. Swapping data of nodes may be expensive in many situations when the data contains many fields. In this post, a solution that performs conversion by swapping links is discussed.
The idea is to traverse the given linked list and check if current node maintains the zigzag order or not. To check if given node maintains zigzag order or not, a variable ind is used. If ind = 0, then the current node’s data should be less than its adjacent node’s data and if ind = 1, then current node’s data should be greater than its adjacent node’s data. If the current node violates the zigzag order, then swap the position of both nodes. For doing this step, maintain two pointers prev and next. prev stores previous node of current node and next stores new next node of current node. To swap both nodes, the following steps are performed:
- Make next node of current node, the next node of previous node.
- Make the current node next node of its adjacent node.
- Make current node next = next node.
Below is the implementation of above approach:
Given linked list 4->3->7->8->6->2->1-> Zig Zag Linked list 3->7->4->8->2->6->1->
Time Complexity: O(N)
Auxiliary Space: O(1)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Rearrange a given linked list in-place.
- Subtree of all nodes in a tree using DFS
- Find the maximum node at a given level in a binary tree
- Maximize the total profit of all the persons
- Reverse nodes of a linked list without affecting the special characters
- Pair with minimum absolute difference after solving each query
- Sum of cousins of a given node in a Binary Tree
- Applications of Graph Data Structure
- Insert a node at a specific position in a linked list
- Queries to insert, delete one occurrence of a number and print the least and most frequent element