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
Output: 1->3->2->4
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
Output: 11->20->5->15->10
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.
C++
#include<bits/stdc++.h>usingnamespacestd;// Structure of linked list nodeclassNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*zigZag(Node*head){if(head==nullptr)returnhead;boolswapped=true;// Repeat until no swaps are neededwhile(swapped){swapped=false;Node*current=head;boolflag=true;// Traverse linked listwhile(current!=nullptr&¤t->next!=nullptr){// If flag is true, next element// should be greater than currentif(flag){if(current->data>current->next->data){swap(current->data,current->next->data);swapped=true;}}// If flag is false, next element// should be smaller than currentelse{if(current->data<current->next->data){swap(current->data,current->next->data);swapped=true;}}current=current->next;// Flip flag for alternate checkingflag=!flag;}}returnhead;}// Driver codeintmain(){// LinkedList: 11->15->20->5->10Node*head=newNode(11);head->next=newNode(15);head->next->next=newNode(20);head->next->next->next=newNode(5);head->next->next->next->next=newNode(10);head=zigZag(head);Node*current=head;while(current!=nullptr){cout<<current->data<<" ";current=current->next;}return0;}
Java
importjava.util.*;// Structure of linked list nodeclassNode{publicintdata;publicNodenext;Node(intx){data=x;next=null;}};publicclassGfG{// Function to rearrange linked list in zig-zag fashionstaticNodezigZag(Nodehead){if(head==null)returnhead;booleanswapped=true;// Repeat until no swaps are neededwhile(swapped){swapped=false;Nodecurrent=head;booleanflag=true;// Traverse linked listwhile(current!=null&¤t.next!=null){// If flag is true, next element// should be greater than currentif(flag){if(current.data>current.next.data){inttemp=current.data;current.data=current.next.data;current.next.data=temp;swapped=true;}}// If flag is false, next element// should be smaller than currentelse{if(current.data<current.next.data){inttemp=current.data;current.data=current.next.data;current.next.data=temp;swapped=true;}}current=current.next;// Flip flag for alternate checkingflag=!flag;}}returnhead;}// Driver codepublicstaticvoidmain(String[]args){// LinkedList: 11->15->20->5->10Nodehead=newNode(11);head.next=newNode(15);head.next.next=newNode(20);head.next.next.next=newNode(5);head.next.next.next.next=newNode(10);head=zigZag(head);Nodecurrent=head;while(current!=null){System.out.print(current.data+" ");current=current.next;}}}
Python
# Structure of linked list nodeclassNode:def__init__(self,x):self.data=xself.next=None# Function to rearrange linked list in zig-zag fashiondefzigZag(head):ifheadisNone:returnheadswapped=True# Repeat until no swaps are neededwhileswapped:swapped=Falsecurrent=headflag=True# Traverse linked listwhilecurrentisnotNoneandcurrent.nextisnotNone:# If flag is true, next element# should be greater than currentifflag:ifcurrent.data>current.next.data:current.data,current.next.data=current.next.data,current.dataswapped=True# If flag is false, next element# should be smaller than currentelse:ifcurrent.data<current.next.data:current.data,current.next.data=current.next.data,current.dataswapped=Truecurrent=current.next# Flip flag for alternate checkingflag=notflagreturnhead# Driver codeif__name__=='__main__':# LinkedList: 11->15->20->5->10head=Node(11)head.next=Node(15)head.next.next=Node(20)head.next.next.next=Node(5)head.next.next.next.next=Node(10)head=zigZag(head)# Print the rearranged linked listcurrent=headwhilecurrentisnotNone:print(current.data,end=' ')current=current.next
C#
usingSystem;// Structure of linked list nodepublicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}publicclassGfG{publicstaticNodezigZag(Nodehead){if(head==null)returnhead;boolswapped=true;// Repeat until no swaps are neededwhile(swapped){swapped=false;Nodecurrent=head;boolflag=true;// Traverse linked listwhile(current!=null&¤t.next!=null){// If flag is true, next element// should be greater than currentif(flag){if(current.data>current.next.data){inttemp=current.data;current.data=current.next.data;current.next.data=temp;swapped=true;}}// If flag is false, next element// should be smaller than currentelse{if(current.data<current.next.data){inttemp=current.data;current.data=current.next.data;current.next.data=temp;swapped=true;}}current=current.next;// Flip flag for alternate checkingflag=!flag;}}returnhead;}// Driver codepublicstaticvoidMain(){// LinkedList: 11->15->20->5->10Nodehead=newNode(11);head.next=newNode(15);head.next.next=newNode(20);head.next.next.next=newNode(5);head.next.next.next.next=newNode(10);head=zigZag(head);Nodecurrent=head;while(current!=null){Console.Write(current.data+" ");current=current.next;}}}
JavaScript
// Structure of linked list nodeclassNode{constructor(x){this.data=x;this.next=null;}}functionzigZag(head){if(head===null)returnhead;letswapped=true;// Repeat until no swaps are neededwhile(swapped){swapped=false;letcurrent=head;letflag=true;// Traverse linked listwhile(current!==null&¤t.next!==null){// If flag is true, next element// should be greater than currentif(flag){if(current.data>current.next.data){[current.data,current.next.data]=[current.next.data,current.data];swapped=true;}}// If flag is false, next element// should be smaller than currentelse{if(current.data<current.next.data){[current.data,current.next.data]=[current.next.data,current.data];swapped=true;}}current=current.next;// Flip flag for alternate checkingflag=!flag;}}returnhead;}// Driver code// LinkedList: 11->15->20->5->10lethead=newNode(11);head.next=newNode(15);head.next.next=newNode(20);head.next.next.next=newNode(5);head.next.next.next.next=newNode(10);head=zigZag(head);letcurrent=head;while(current!==null){console.log(current.data);current=current.next;}
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 10 (>= needed), condition satisfied.
Final List: 11 -> 20 -> 5 -> 15 -> 10
C++
#include<bits/stdc++.h>usingnamespacestd;// Structure of linked list nodeclassNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*zigZag(Node*head){boolflag=true;// Traverse linked list starting from head.Node*current=head;while(current!=nullptr&¤t->next!=nullptr){if(flag){// flag == true indicates next element// should be larger than currentif(current->data>current->next->data)swap(current->data,current->next->data);}else{// flag == false indicates next element// should be smaller than currentif(current->data<current->next->data)swap(current->data,current->next->data);}current=current->next;// Flip flag for reverse checkingflag=!flag;}returnhead;}// Driver codeintmain(){// LinkedList: 11->15->20->5->10Node*head=newNode(11);head->next=newNode(15);head->next->next=newNode(20);head->next->next->next=newNode(5);head->next->next->next->next=newNode(10);head=zigZag(head);// Print listNode*current=head;while(current!=nullptr){cout<<current->data<<" -> ";current=current->next;}cout<<"NULL";return0;}
Java
classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGFG{staticNodezigZag(Nodehead){booleanflag=true;// Traverse linked list starting from head.Nodecurrent=head;while(current!=null&¤t.next!=null){if(flag){// flag == true indicates next element// should be larger than currentif(current.data>current.next.data){inttemp=current.data;current.data=current.next.data;current.next.data=temp;}}else{// flag == false indicates next element// should be smaller than currentif(current.data<current.next.data){inttemp=current.data;current.data=current.next.data;current.next.data=temp;}}current=current.next;// Flip flag for reverse checkingflag=!flag;}returnhead;}// Driver codepublicstaticvoidmain(String[]args){// LinkedList: 11->15->20->5->10Nodehead=newNode(11);head.next=newNode(15);head.next.next=newNode(20);head.next.next.next=newNode(5);head.next.next.next.next=newNode(10);head=zigZag(head);// Print listNodecurrent=head;while(current!=null){System.out.print(current.data+" -> ");current=current.next;}System.out.println("null");}}
Python
# Structure of linked list nodeclassNode:def__init__(self,x):self.data=xself.next=NonedefzigZag(head):flag=True# Traverse linked list starting from head.current=headwhilecurrentisnotNoneandcurrent.nextisnotNone:ifflag:# flag == true indicates next element# should be larger than currentifcurrent.data>current.next.data:current.data,current.next.data=current.next.data,current.dataelse:# flag == false indicates next element# should be smaller than currentifcurrent.data<current.next.data:current.data,current.next.data=current.next.data,current.datacurrent=current.next# Flip flag for reverse checkingflag=notflagreturnhead# Driver codeif__name__=="__main__":# LinkedList: 11->15->20->5->10head=Node(11)head.next=Node(15)head.next.next=Node(20)head.next.next.next=Node(5)head.next.next.next.next=Node(10)head=zigZag(head)# Print the listcurrent=headwhilecurrentisnotNone:print(current.data,end=' ')current=current.nextprint()
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGFG{staticNodezigZag(Nodehead){boolflag=true;// Traverse linked list starting from head.Nodecurrent=head;while(current!=null&¤t.next!=null){if(flag){// flag == true indicates next element// should be larger than currentif(current.data>current.next.data){inttemp=current.data;current.data=current.next.data;current.next.data=temp;}}else{// flag == false indicates next element// should be smaller than currentif(current.data<current.next.data){inttemp=current.data;current.data=current.next.data;current.next.data=temp;}}current=current.next;// Flip flag for reverse checkingflag=!flag;}returnhead;}// Driver codestaticvoidMain(){// LinkedList: 11->15->20->5->10Nodehead=newNode(11);head.next=newNode(15);head.next.next=newNode(20);head.next.next.next=newNode(5);head.next.next.next.next=newNode(10);head=zigZag(head);Nodecurrent=head;while(current!=null){Console.Write(current.data+" ");current=current.next;}}}
JavaScript
// Structure of linked list nodeclassNode{constructor(x){this.data=x;this.next=null;}}functionzigZag(head){letflag=true;// Traverse linked list starting from head.letcurrent=head;while(current!==null&¤t.next!==null){if(flag){// flag == true indicates next element// should be larger than currentif(current.data>current.next.data){[current.data,current.next.data]=[current.next.data,current.data];}}else{// flag == false indicates next element// should be smaller than currentif(current.data<current.next.data){[current.data,current.next.data]=[current.next.data,current.data];}}current=current.next;// Flip flag for reverse checkingflag=!flag;}returnhead;}// Driver code// LinkedList: 11->15->20->5->10lethead=newNode(11);head.next=newNode(15);head.next.next=newNode(20);head.next.next.next=newNode(5);head.next.next.next.next=newNode(10);head=zigZag(head);// Function to print the linked listfunctionprintList(head){letcurrent=head;while(current!==null){console.log(current.data);current=current.next;}}// Print the modified listprintList(head);