Sort a linked list of 0s, 1s and 2s GFG problem

 Given a linked list 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 the head side, 2s at the end of the linked list, and 1s in the middle of 0s and 2s.


Examples:


Input: LinkedList: 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.

 

Input: LinkedList: 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.


Expected Time Complexity: O(n).

Expected Auxiliary Space: O(n).




class Solution {

    // Function to sort a linked list of 0s, 1s and 2s.

    static Node segregate(Node head) {

        // add your code here

       if (head == null || head.next == null) return head;


        // Step 1: Count occurrences of 0s, 1s, and 2s

        int count0 = 0, count1 = 0, count2 = 0;

        Node temp = head;


        while (temp != null) {

            if (temp.data == 0) count0++;

            else if (temp.data == 1) count1++;

            else count2++;

            temp = temp.next;

        }

        

         temp = head;

        

       

       while(count0 -- >0)

       {

           temp.data=0;

           temp=temp.next;

       }

         while(count1 -- >0)

       {

           temp.data=1;

           temp=temp.next;

       }

         while(count2 -- >0)

       {

           temp.data=2;

           temp=temp.next;

       }

       

       return head;

    }

}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence