Given a linked list of 0s, 1s and 2s, sort it. | Practice | GeeksforGeeks

Given a linked list of N nodes where nodes can contain values 0s, 1s, and 2s only. The task is to segregate 0s, 1s, and 2s linked list such that all zeros segregate to head side, 2s at the end of the linked list, and 1s in the mid of 0s and 2s.
Example 1:
Input:
N = 8
value[] = {1,2,2,1,2,0,2,2}
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.

Example 2:
Input:
N = 4
value[] = {2,2,0,1}
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.
Your Task:
The task is to complete the function segregate() which segregates the nodes in the linked list as asked in the problem statement and returns the head of the modified linked list. The printing is done automatically by the driver code.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 <= N <= 103
0
tasnimzotder2 days ago
C++ Solution
        Node* curr = head;

        Node* p0_Node = new Node(-1);
        Node* p_0 = p0_Node;

        Node* p1_Node = new Node(-1);
        Node* p_1 = p1_Node;

        Node* p2_Node = new Node(1);
        Node* p_2 = p2_Node;

        while (curr != NULL) {
            if (curr->data == 0) {
                p_0->next = new Node(curr->data);
                p_0 = p_0->next;
            } else if (curr->data == 1) {
                p_1->next = new Node(curr->data);

                p_1 = p_1->next;

            } else {
                p_2->next = new Node(curr->data);

                p_2 = p_2->next;
            }

            curr = curr->next;
        }

        p_0->next = p1_Node->next;
        if (p_1 == p1_Node) {
            p_0->next = p2_Node->next;
        } else {
            p_1->next = p2_Node->next;
        }

        return p0_Node->next;
0
shrays6502 days ago
Python code
def segregate(self, head):       #code here       node=head       lst=[]       while node:           lst.append(node.data)           node=node.next       lst.sort()       head1=Node(lst[0])       node1=head1       for i in range(1,len(lst)):           newNode=Node(lst[i])           node1.next=newNode           node1=newNode       return head1
0
09himanshusah5 days ago
JavaScript Solution
class Solution {
    //Function to sort a linked list of 0s, 1s and 2s.
    segregate(head)
    {
        //your code here
        let zero = new Node(-1);
        let t0 = zero;
        let one = new Node(-1);
        let t1 = one;
        let two = new Node(-1);
        let t2 = two;
        
        let cur = head;
        while(cur !== null) {
            if(cur.data === 0) {
                t0.next = cur;
                t0 = t0.next;
            } else if(cur.data === 1) {
                t1.next = cur;
                t1 = t1.next;
            } else if(cur.data === 2) {
                t2.next = cur;
                t2 = t2.next;
            }
            cur = cur.next;
        }
        if(one.next === null) {
            t0.next = two.next;
            t2.next = null;
            return zero.next;
        }
        if(zero.next === null) {
            t1.next = two.next;
            t2.next = null;
            return one.next;
        }
        if(two.next === null) {
            t0.next = one.next;
            t1.next = null;
            return zero.next;
        }
        t0.next = one.next;
        t1.next = two.next;
        t2.next = null;
        return zero.next;
    }
}
+1
swapniltayal4221 week ago
class Solution{   public:   //Function to sort a linked list of 0s, 1s and 2s.   Node* segregate(Node *head) {              // Add code here       int zero = 0;       int one = 0;       int two = 0;       Node* temp = head;       while(temp){           if (temp->data == 1){               one++;           }else if(temp->data == 2){               two++;           }else{               zero++;           }temp = temp->next;       }       temp = head;       while(zero--){           temp->data = 0;           temp = temp->next;       }while(one--){           temp->data = 1;           temp = temp->next;       }while(two--){           temp->data = 2;           temp = temp->next;       }       return head;          }};
-1
arifmohammadarif07861 week ago
Simple C++ Solution 0.02
 
Node* segregate(Node *head) {              // Add code here       Node* curr=head;       vector<int>arr;              int a=0,b=0,c=0;       while(curr){                  if(curr->data==0)           {           a++;           }                      else if(curr->data==1)           {           b++;           }                      else{           c++;           }                      curr=curr->next;       }       for(int i=0;i<a;i++)       {       arr.push_back(0);       }              for(int i=a;i<a+b;i++)       {       arr.push_back(1);       }              for(int i=a+b;i<a+b+c;i++)       {       arr.push_back(2);       }              Node* head1=new Node(0);       Node* temp=head1;              for(auto i:arr)       {           Node* x= new Node (i);           temp->next=x;           temp=temp->next;       }       return head1->next;   }};
+1
sbbarse21211 week ago
    //Function to sort a linked list of 0s, 1s and 2s.   Node* segregate(Node *head) {      // From Here we prepend all 1's in the start of LinkedList      Node* fast = (head)->next;   Node* slow = head;   Node* temp = NULL;      while(fast){      if(fast->data==1){          temp = fast;                    fast = fast->next;          temp->next = head;          slow->next = fast;          head = temp;      }else{          slow = fast;          fast = fast->next;              }              }       // From Here we prepend all 0's in the start of LinkedList        Node* fst = head->next;   Node* slw = head;   Node* temp1 = NULL;      while(fst){     if(fst->data==0){         temp1 = fst;                   fst = fst->next;         temp1->next = head;         slw->next = fst;         head = temp1;     }else{         slw = fst;         fst = fst->next;              }           }      return head;   }
+1
rahul01312 weeks ago
Very simple Code to Understand ||  C++
 
Node* segregate(Node *head) {
       
       // Add code here
       int ZeroCnt = 0;
       int OneCnt = 0;
       int TwoCnt = 0;
       
       Node* temp = head;
       while(temp != NULL){
           if(temp -> data == 0)
           ZeroCnt++;
           
           else if(temp -> data == 1)
           OneCnt++;
           
           else if(temp -> data == 2)
           TwoCnt++;
           
           temp = temp -> next;
       }
       
       temp = head;
       
       while(temp != NULL) {
           if(ZeroCnt != 0){
           temp -> data = 0;
           ZeroCnt--;
           }
           
           else if( OneCnt != 0){
           temp -> data = 1;
           OneCnt--;
           }
           
           else if(TwoCnt != 0){
           temp -> data = 2;
           TwoCnt--;
           }
           temp  = temp -> next;
       }
       return head;
   }
0
anmol rawat2 weeks ago
class Solution{   public:   //Function to sort a linked list of 0s, 1s and 2s.   Node* segregate(Node *head) {       // Add code here       int arr[3]={0};       Node *curr=head;       while(curr){           arr[curr->data]++;           curr=curr->next;       }       curr=head;       int x=0;       while(curr){           while(arr[x]--){               curr->data=x;               curr=curr->next;           }           x++;       }       return head;   }};
0
dev1713 weeks ago
C++ Actually rearranging nodes
  Node* segregate(Node *head) {
        
        // Add code here
        if(!head || !head->next)
        return head;
        
        Node *zeros=new Node(-1),*ones=new Node(-1),*twos=new Node(-1);
        Node *lz=zeros,*lo=ones,*lt=twos;
        Node *cur=head;
        while(cur){
            if(cur->data==0){
                lz->next=cur;
                lz=cur;
            }else if(cur->data==1){
                lo->next=cur;
                lo=cur;
            }else{
                lt->next=cur;
                lt=cur;
            }
            cur=cur->next;
        }
        if(lo!=ones){
            lz->next=ones->next;
            lo->next=twos->next;
        }else{
            lz->next=twos->next;
        }
         lt->next=NULL;
         return zeros->next;
    }
+1
sbshivam01613 weeks ago
// Java Solution
class Solution
{
    //Function to sort a linked list of 0s, 1s and 2s.
    static Node segregate(Node head)
    {
         int zeroes = 0; 
         int ones = 0;
         int twos = 0;
         
         Node dummyNode = head;
         
         
         while(dummyNode!=null)
         {
             if(dummyNode.data == 0)
             {
                 zeroes++;
             }
             else if(dummyNode.data == 1)
             {
                 ones++;
             }
             else
             {
                 twos++;
             }
             
             dummyNode = dummyNode.next;
         }
         
         dummyNode = head;
         
         while(dummyNode!=null)
         {
              if(zeroes!=0)
              {
                  dummyNode.data = 0;
                  zeroes--;
              }
              else if(ones!=0)
              {
                  dummyNode.data = 1;
                  ones--;
              }
              else
              {
                  dummyNode.data = 2;
                  twos--;
              }
              
              dummyNode = dummyNode.next;
         }
         
         return head;
    }
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.