Given a head of linked list containing nodes with values 0, 1, and 2 only, rearrange the list so that all 0s appear first, followed by all 1s, and then all 2s at the end, while maintaining the relative order within each group.
Examples:
Input:
Output: 0 -> 1 ->1 ->2 ->2 -> 2 -> 2 -> 2 Explanation: All the 0s are segregated to the left end of the linked list, 2s to the right end of the list, and 1s in between.
Input:
Output: 0 ->1 -> 2 -> 2 Explanation: After arranging all the 0s, 1s and 2s in the given format, the output will be 0 -> 1 -> 2 -> 2.
The idea is to traverse the linked list and count the occurrences of 0, 1, and 2 using an array cnt[] of size 3. Then, traverse the list again and update the node values by placing all 0s first, followed by 1s and then 2s.
cnt[0] stores the count of nodes having value 0.
cnt[1] stores the count of nodes having value 1.
cnt[2] stores the count of nodes having value 2.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};Node*segregate(Node*head){intcnt[3]={0,0,0};Node*curr=head;// Count occurrences of 0, 1 and 2while(curr){cnt[curr->data]++;curr=curr->next;}curr=head;intidx=0;// Update node values in sorted orderwhile(curr){if(cnt[idx]==0){idx++;}else{curr->data=idx;cnt[idx]--;curr=curr->next;}}returnhead;}intmain(){Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(2);head->next->next->next=newNode(1);head->next->next->next->next=newNode(2);head->next->next->next->next->next=newNode(0);head->next->next->next->next->next->next=newNode(2);head->next->next->next->next->next->next->next=newNode(2);head=segregate(head);while(head!=nullptr){cout<<head->data;if(head->next!=nullptr){cout<<" -> ";}head=head->next;}cout<<"\n";return0;}
Java
importjava.util.*;classNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}publicclassGFG{staticNodesegregate(Nodehead){int[]cnt={0,0,0};Nodecurr=head;// Count occurrences of 0, 1 and 2while(curr!=null){cnt[curr.data]++;curr=curr.next;}curr=head;intidx=0;// Update node values in sorted orderwhile(curr!=null){if(cnt[idx]==0){idx++;}else{curr.data=idx;cnt[idx]--;curr=curr.next;}}returnhead;}publicstaticvoidmain(String[]args){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(2);head.next.next.next=newNode(1);head.next.next.next.next=newNode(2);head.next.next.next.next.next=newNode(0);head.next.next.next.next.next.next=newNode(2);head.next.next.next.next.next.next.next=newNode(2);head=segregate(head);while(head!=null){System.out.print(head.data);if(head.next!=null){System.out.print(" -> ");}head=head.next;}System.out.println();}}
Python
classNode:def__init__(self,new_data):self.data=new_dataself.next=Nonedefsegregate(head):cnt=[0,0,0]curr=head# Count occurrences of 0, 1 and 2whilecurrisnotNone:cnt[curr.data]+=1curr=curr.nextcurr=headidx=0# Update node values in sorted orderwhilecurrisnotNone:ifcnt[idx]==0:idx+=1else:curr.data=idxcnt[idx]-=1curr=curr.nextreturnheaddefprintList(node):whilenodeisnotNone:print(node.data,end=" -> "ifnode.nextisnotNoneelse"\n")node=node.nextif__name__=='__main__':head=Node(1)head.next=Node(2)head.next.next=Node(2)head.next.next.next=Node(1)head.next.next.next.next=Node(2)head.next.next.next.next.next=Node(0)head.next.next.next.next.next.next=Node(2)head.next.next.next.next.next.next.next=Node(2)head=segregate(head)printList(head)
C#
usingSystem;publicclassNode{publicintdata;publicNodenext;publicNode(intnew_data){data=new_data;next=null;}}publicclassGFG{staticNodesegregate(Nodehead){int[]cnt={0,0,0};Nodecurr=head;// Count occurrences of 0, 1 and 2while(curr!=null){cnt[curr.data]++;curr=curr.next;}curr=head;intidx=0;// Update node values in sorted orderwhile(curr!=null){if(cnt[idx]==0){idx++;}else{curr.data=idx;cnt[idx]--;curr=curr.next;}}returnhead;}staticvoidMain(){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(2);head.next.next.next=newNode(1);head.next.next.next.next=newNode(2);head.next.next.next.next.next=newNode(0);head.next.next.next.next.next.next=newNode(2);head.next.next.next.next.next.next.next=newNode(2);head=segregate(head);while(head!=null){Console.Write(head.data);if(head.next!=null){Console.Write(" -> ");}head=head.next;}Console.WriteLine();}}
JavaScript
classNode{constructor(new_data){this.data=new_data;this.next=null;}}functionsegregate(head){letcnt=[0,0,0];letcurr=head;// Count occurrences of 0, 1 and 2while(curr!==null){cnt[curr.data]++;curr=curr.next;}curr=head;letidx=0;// Update node values in sorted orderwhile(curr!==null){if(cnt[idx]===0){idx++;}else{curr.data=idx;cnt[idx]--;curr=curr.next;}}returnhead;}functionprintList(node){while(node!==null){process.stdout.write(node.data);if(node.next!==null){process.stdout.write(" -> ");}node=node.next;}console.log();}// Driver Codelethead=newNode(1);head.next=newNode(2);head.next.next=newNode(2);head.next.next.next=newNode(1);head.next.next.next.next=newNode(2);head.next.next.next.next.next=newNode(0);head.next.next.next.next.next.next=newNode(2);head.next.next.next.next.next.next.next=newNode(2);head=segregate(head);while(head){process.stdout.write(String(head.data));if(head.next){process.stdout.write(" -> ");}head=head.next;}console.log();
Output
0 -> 1 -> 1 -> 2 -> 2 -> 2 -> 2 -> 2
Changing Links of Nodes - O(n) Time and O(1) Space
The idea is to create three separate linked lists for nodes containing 0, 1, and 2, then connect these lists in the required order. This is mainly based on Dutch National Flag algorithm.
If the current node's value is 0, append it to the list of 0s and move the zero pointer to the current node.
If the current node's value is 1, append it to the list of 1s and move the one pointer to the current node.
If the current node's value is 2, append it to the list of 2s and move the two pointer to the current node.
Finally, connect the three lists in the order 0, 1, and 2. To avoid handling empty lists separately, use three dummy nodes, zeroD, oneD, and twoD, as the starting points of the lists.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};Node*segregate(Node*head){// Create dummy nodes for the three lists.NodezeroD(0),oneD(0),twoD(0);Node*zero=&zeroD,*one=&oneD,*two=&twoD;Node*curr=head;// Divide nodes into lists based on their values.while(curr){Node*nextNode=curr->next;if(curr->data==0){zero->next=curr;zero=zero->next;}elseif(curr->data==1){one->next=curr;one=one->next;}else{two->next=curr;two=two->next;}// Move to the next node in the original list.curr=nextNode;}// Connect the three lists in the order 0, 1, and 2.zero->next=oneD.next?oneD.next:twoD.next;one->next=twoD.next;two->next=nullptr;// Return the head of the rearranged list.returnzeroD.next;}intmain(){Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(2);head->next->next->next=newNode(1);head->next->next->next->next=newNode(2);head->next->next->next->next->next=newNode(0);head->next->next->next->next->next->next=newNode(2);head->next->next->next->next->next->next->next=newNode(2);head=segregate(head);while(head!=nullptr){cout<<head->data;if(head->next!=nullptr){cout<<" -> ";}head=head->next;}cout<<"\n";return0;}
Java
importjava.util.*;classNode{publicintdata;publicNodenext;publicNode(intnew_data){data=new_data;next=null;}}publicclassGFG{Nodesegregate(Nodehead){// Create dummy nodes for the three lists.NodezeroD=newNode(0),oneD=newNode(0),twoD=newNode(0);Nodezero=zeroD,one=oneD,two=twoD;Nodecurr=head;// Divide nodes into lists based on their values.while(curr!=null){NodenextNode=curr.next;if(curr.data==0){zero.next=curr;zero=zero.next;}elseif(curr.data==1){one.next=curr;one=one.next;}else{two.next=curr;two=two.next;}// Move to the next node in the original list.curr=nextNode;}// Connect the three lists in the order 0, 1, and 2.zero.next=(oneD.next!=null)?oneD.next:twoD.next;one.next=twoD.next;two.next=null;// Return the head of the rearranged list.returnzeroD.next;}publicstaticvoidmain(String[]args){GFGmain=newGFG();Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(2);head.next.next.next=newNode(1);head.next.next.next.next=newNode(2);head.next.next.next.next.next=newNode(0);head.next.next.next.next.next.next=newNode(2);head.next.next.next.next.next.next.next=newNode(2);head=main.segregate(head);while(head!=null){System.out.print(head.data);if(head.next!=null){System.out.print(" -> ");}head=head.next;}System.out.println();}}
Python
classNode:def__init__(self,new_data):self.data=new_dataself.next=Nonedefsegregate(head):# Create dummy nodes for the three lists.zeroD=Node(0)oneD=Node(0)twoD=Node(0)zero=zeroDone=oneDtwo=twoDcurr=head# Divide nodes into lists based on their values.whilecurr:nextNode=curr.nextifcurr.data==0:zero.next=currzero=zero.nextelifcurr.data==1:one.next=currone=one.nextelse:two.next=currtwo=two.next# Move to the next node in the original list.curr=nextNode# Connect the three lists in the order 0, 1, and 2.zero.next=oneD.nextifoneD.nextelsetwoD.nextone.next=twoD.nexttwo.next=None# Return the head of the rearranged list.returnzeroD.nextif__name__=='__main__':head=Node(1)head.next=Node(2)head.next.next=Node(2)head.next.next.next=Node(1)head.next.next.next.next=Node(2)head.next.next.next.next.next=Node(0)head.next.next.next.next.next.next=Node(2)head.next.next.next.next.next.next.next=Node(2)head=segregate(head)whilehead:print(head.data,end='')ifhead.next:print(' -> ',end='')head=head.nextprint()
C#
usingSystem;publicclassNode{publicintdata;publicNodenext;publicNode(intnew_data){data=new_data;next=null;}}publicclassGFG{publicNodesegregate(Nodehead){// Create dummy nodes for the three lists.NodezeroD=newNode(0),oneD=newNode(0),twoD=newNode(0);Nodezero=zeroD,one=oneD,two=twoD;Nodecurr=head;// Divide nodes into lists based on their values.while(curr!=null){NodenextNode=curr.next;if(curr.data==0){zero.next=curr;zero=zero.next;}elseif(curr.data==1){one.next=curr;one=one.next;}else{two.next=curr;two=two.next;}// Move to the next node in the original list.curr=nextNode;}// Connect the three lists in the order 0, 1, and 2.zero.next=oneD.next!=null?oneD.next:twoD.next;one.next=twoD.next;two.next=null;// Return the head of the rearranged list.returnzeroD.next;}publicstaticvoidMain(){GFGprogram=newGFG();Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(2);head.next.next.next=newNode(1);head.next.next.next.next=newNode(2);head.next.next.next.next.next=newNode(0);head.next.next.next.next.next.next=newNode(2);head.next.next.next.next.next.next.next=newNode(2);head=program.segregate(head);while(head!=null){Console.Write(head.data);if(head.next!=null)Console.Write(" -> ");head=head.next;}Console.WriteLine();}}
JavaScript
classNode{constructor(new_data){this.data=new_data;this.next=null;}}functionsegregate(head){// Create dummy nodes for the three lists.letzeroD=newNode(0),oneD=newNode(0),twoD=newNode(0);letzero=zeroD,one=oneD,two=twoD;letcurr=head;// Divide nodes into lists based on their values.while(curr){letnextNode=curr.next;if(curr.data===0){zero.next=curr;zero=zero.next;}elseif(curr.data===1){one.next=curr;one=one.next;}else{two.next=curr;two=two.next;}// Move to the next node in the original list.curr=nextNode;}// Connect the three lists in the order 0, 1, and 2.zero.next=oneD.next?oneD.next:twoD.next;one.next=twoD.next;two.next=null;// Return the head of the rearranged list.returnzeroD.next;}// Driver Codelethead=newNode(1);head.next=newNode(2);head.next.next=newNode(2);head.next.next.next=newNode(1);head.next.next.next.next=newNode(2);head.next.next.next.next.next=newNode(0);head.next.next.next.next.next.next=newNode(2);head.next.next.next.next.next.next.next=newNode(2);head=segregate(head);while(head){process.stdout.write(String(head.data));if(head.next){process.stdout.write(" -> ");}head=head.next;}console.log();