{"id":4327,"date":"2021-08-25T08:43:32","date_gmt":"2021-08-25T08:43:32","guid":{"rendered":"https:\/\/www.prepbytes.com\/blog\/?p=4327"},"modified":"2022-11-18T07:19:40","modified_gmt":"2022-11-18T07:19:40","slug":"sort-a-linked-list-of-0s-1s-and-2s-by-changing-links","status":"publish","type":"post","link":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/","title":{"rendered":"Sort a linked list of 0s, 1s, and 2s by changing links"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926302503-113.Sort%20a%20linked%20list%20of%200s%2C%201s%2C%20and%202s%20by%20changing%20links_Artboard%202.png\" alt=\"\" \/><\/p>\n<p>In this article, we will learn to sort a linked list of 0s 1s and 2s. Sorting an array implies that the elements present in the array must be present in a particular order, whether in ascending order or in descending order. Let\u2019s try to understand to sort linked list of 0 1 2 <\/p>\n<\/p>\n<h3>Problem Statement<\/h3>\n<p>In this problem, we are given a linked list containing 0s, 1s, and 2s, and we are required to sort this linked list. <\/p>\n<h5>Example<\/h5>\n<p>Input:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/input-14.png\" alt=\"\" \/><\/p>\n<p>Output:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/example-output-5.png\" alt=\"\" \/><\/p>\n<h3>Problem Statement Understanding to sort a linked list of 0s 1s and 2s<\/h3>\n<p>Let\u2019s learn programming languages online and try to understand to sort linked of 01 2 <\/p>\n<p>Suppose we are given a linked list 1 \u2192 2 \u2192 0 \u2192 1 \u2192 0 \u2192 NULL, now the problem is demanding that we have to sort the linked list such that our original linked list after sorting  should look like:<br \/>\nFinal resultant linked list after sorting:-  0 \u2192 0 \u2192 1 \u2192 1 \u2192 2   \u2192 NULL<\/p>\n<p><strong>Explanation:<\/strong> So basically we have to sort the linked list such that in the final sorted linked list all the nodes with value 0 come before the nodes with value 1 and all the nodes with value 1 comes before the nodes with value 2.<\/p>\n<p>Say if the input linked list is<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/example-input-5.png\" alt=\"\" \/><\/p>\n<p>now in this case after sorting the input linked list our final linked list will look like:<br \/>\nFinal resultant linked list after sorting:-<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/example-output-5.png\" alt=\"\" \/><\/p>\n<p>So now I think from the above examples it is clear what the problem is demanding to sort a linked list of 0 1 2.<\/p>\n<p>Let\u2019s think how we can approach to sort a linked list of 0s 1s and 2s.<\/p>\n<h3>Approach 1 to sort linked list of 0 1 2<\/h3>\n<p>As we can see in the problem our linked list only contains nodes with values 0, 1, and 2, so one simple solution will be to count the number of 0&#8217;s, 1&#8217;s, and 2&#8217;s. <\/p>\n<ul>\n<li>\n<p>After counting the number of 0&#8217;s, 1&#8217;s, and 2&#8217;s, fill the first P (where P is count of 0&#8217;s) nodes with 0, then next Q (where Q is count of 1&#8217;s) nodes with 1 and last R (where R is count of 2&#8217;s) nodes with 2.<\/p>\n<\/li>\n<li>\n<p>After filling the nodes with 0&#8217;s, 1&#8217;s, and 2&#8217;s, our final linked list will be sorted, and we will get our desired result. <\/p>\n<\/li>\n<\/ul>\n<p>But there is one problem, that this solution does not work when these values have associated data with them. <\/p>\n<ul>\n<li>For example, If these three 0&#8217;s, 1&#8217;s, and 2&#8217;s represent three different colors and with these colors different types of objects have been associated and have to sort the objects based on colors.<\/li>\n<\/ul>\n<p>So now we will see how can we solve this problem and finally sort the list.<\/p>\n<h3>Approach 2 to sort linked list of 0 1 2<\/h3>\n<p>The above problem could be solved by changing the links:<\/p>\n<ul>\n<li>If we can change the links of nodes such that all the nodes having value of 0 gets together and forms a separate linked list containing all the nodes with value 0. Similarly, the nodes with values 1 and 2 also get together and form their separate linked list.<\/li>\n<li>After separate linked lists for  0&#8217;s, 1&#8217;s, and 2&#8217;s have been formed:<br \/>\n1) We will make the head of the linked list containing 0&#8217;s the head of the final sorted linked list.<br \/>\n2) We will make the tail of the linked list of 0&#8217;s point to the head of the linked list of 1&#8217;s and the tail of the linked list of 1&#8217;s point to the head of the linked list of 2&#8217;s.<br \/>\n3) Also, we will make the tail of the linked list of 2&#8217;s point to NULL.<\/li>\n<li>Finally, we can return our final sorted linked list by returning the head of a linked list of 0&#8217;s.<\/li>\n<\/ul>\n<h3>Algorithm to sort a linked list of 0s 1s and 2s<\/h3>\n<ul>\n<li>Traverse through the list one by one. <\/li>\n<li>Maintain three pointers designated <strong>ptr0<\/strong>, <strong>ptr1<\/strong>, and <strong>ptr2<\/strong> that refer to the current ending nodes of linked lists with 0, 1, and 2 elements, respectively. <\/li>\n<li>We append each explored Node to the end of its associated list:<br \/>\n1) Node with value 0 will be appended to the end of linked list of 0&#8217;s.<br \/>\n2) Node with value 1 will be appended to end of linked list of 1&#8217;s.<br \/>\n3) Node with value 2 will be appended to the end of linked lists of 2&#8217;s.<\/li>\n<li>Finally, we join the three lists together. For joining the three lists together we will utilize three dummy pointers <strong>temp0<\/strong>, <strong>temp1<\/strong>, and <strong>temp2<\/strong> that act as dummy headers for the three lists to avoid multiple null tests.<\/li>\n<li>Finally, we will return the head of the linked list of 0&#8217;s.<\/li>\n<\/ul>\n<h3>Dry Run to sort a linked list of 0s 1s and 2s<\/h3>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/Sort-a-linked-list-of-0s-1s-and-2s-by-changing-links-1.png\" alt=\"\" \/><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/Sort-a-linked-list-of-0s-1s-and-2s-by-changing-links-2.png\" alt=\"\" \/><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/08\/Sort-a-linked-list-of-0s-1s-and-2s-by-changing-links-3.png\" alt=\"\" \/><\/p>\n<h3>Code Implementation to sort a linked list of 0 1 2<\/h3>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_4328 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_4328 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_4328 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_4328 .wpsm_nav-tabs > li.active > a, #tab_container_4328 .wpsm_nav-tabs > li.active > a:hover, #tab_container_4328 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_4328 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_4328 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_4328 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_4328 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_4328 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_4328 .wpsm_nav-tabs > li > a:hover , #tab_container_4328 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_4328 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_4328 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_4328 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_4328 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_4328 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_4328 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_4328 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_4328 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_4328 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_4328 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_4328 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_4328\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_4328\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_4328_1\" aria-controls=\"tabs_desc_4328_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>C<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_4328_2\" aria-controls=\"tabs_desc_4328_2\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>C++<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_4328_3\" aria-controls=\"tabs_desc_4328_3\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Java<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_4328_4\" aria-controls=\"tabs_desc_4328_4\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Python<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_4328\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_4328_1\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"c\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"c\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\n#include &lt;stdio.h&gt;\r\n#include&lt;stdlib.h&gt;\r\n \r\nstruct Node {\r\n    int data;\r\n    struct Node* next;\r\n};\r\n \r\nstruct Node* newNode(int data);\r\n \r\n\/\/ Sort a linked list of 0s, 1s and 2s\r\n\/\/ by changing pointers.\r\nstruct Node* sortList(struct Node* head)\r\n{\r\n    if (!head || !(head-&gt;next))\r\n        return head;\r\n \r\n    \/\/ Create three dummy nodes to point to\r\n    \/\/ beginning of three linked lists. These\r\n    \/\/ dummy nodes are created to avoid many\r\n    \/\/ null checks.\r\n    struct Node* zeroD = newNode(0);\r\n    struct Node* oneD = newNode(0);\r\n    struct Node* twoD = newNode(0);\r\n \r\n    \/\/ Initialize current pointers for three\r\n    \/\/ lists and whole list.\r\n    struct Node* zero = zeroD, *one = oneD, *two = twoD;\r\n \r\n    \/\/ Traverse list\r\n    struct Node* curr = head;\r\n    while (curr) {\r\n        if (curr-&gt;data == 0) {\r\n            zero-&gt;next = curr;\r\n            zero = zero-&gt;next;\r\n            curr = curr-&gt;next;\r\n        } else if (curr-&gt;data == 1) {\r\n            one-&gt;next = curr;\r\n            one = one-&gt;next;\r\n            curr = curr-&gt;next;\r\n        } else {\r\n            two-&gt;next = curr;\r\n            two = two-&gt;next;\r\n            curr = curr-&gt;next;\r\n        }\r\n    }\r\n \r\n    \/\/ Attach three lists\r\n    zero-&gt;next = (oneD-&gt;next)\r\n? (oneD-&gt;next) : (twoD-&gt;next);\r\n    one-&gt;next = twoD-&gt;next;\r\n    two-&gt;next = NULL;\r\n \r\n    \/\/ Updated head\r\n    head = zeroD-&gt;next;\r\n \r\n    \/\/ Delete dummy nodes\r\n    free(zeroD);\r\n    free(oneD);\r\n    free(twoD);\r\n \r\n    return head;\r\n}\r\n \r\n\/\/ Function to create and return a node\r\nstruct Node* newNode(int data)\r\n{\r\n    \/\/ allocating space\r\n    struct Node* newNode =\r\n         (struct Node*)malloc(sizeof(struct Node));\r\n \r\n    \/\/ inserting the required data\r\n    newNode-&gt;data = data;\r\n    newNode-&gt;next = NULL;\r\n}\r\n \r\n\/* Function to print linked list *\/\r\nvoid printList(struct Node* node)\r\n{\r\n    while (node != NULL) {\r\n        printf(&quot;%d  &quot;, node-&gt;data);\r\n        node = node-&gt;next;\r\n    }\r\n    printf(&quot;&#92;n&quot;);\r\n}\r\n \r\n\/* Driver program to test above function*\/\r\nint main(void)\r\n{\r\n    \/\/ Creating the list 1-&gt;2-&gt;4-&gt;5\r\n    struct Node* head = newNode(1);\r\n    head-&gt;next = newNode(2);\r\n    head-&gt;next-&gt;next = newNode(0);\r\n    head-&gt;next-&gt;next-&gt;next = newNode(1);\r\n \r\n    printf(&quot;Linked List Before Sorting&#92;n&quot;);\r\n    printList(head);\r\n \r\n    head = sortList(head);\r\n \r\n    printf(&quot;Linked List After Sorting&#92;n&quot;);\r\n    printList(head);\r\n \r\n    return 0;\r\n}\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_4328_2\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"cpp\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\n#include &lt;bits\/stdc++.h&gt;\r\nusing namespace std;\r\n\r\n\/* node definition *\/\r\nstruct Node {\r\n    int val;\r\n    struct Node* next;\r\n};\r\n\r\nNode* newNode(int val);\r\n\r\n\/\/ Sorting 0s, 1s and 2s in a linked list\r\nNode* sortingLL(Node* head)\r\n{\r\n    if (!head || !(head-&gt;next))\r\n        return head;\r\n\r\n\/\/ Creating three dummy nodes inorder to point\r\n\/\/ to the starting of the 3 lists. \r\n\/\/ Their motive is to help in avoiding null checks.\r\n    Node* temp0 = newNode(0);\r\n    Node* temp1 = newNode(0);\r\n    Node* temp2 = newNode(0);\r\n\r\n    \/\/ Initialize current pointers\r\n    Node* ptr0 = temp0, *ptr1 = temp1, *ptr2 = temp2;\r\n\r\n    \/\/ Traversing through the list\r\n    Node* current = head;\r\n    while (current) {\r\n        if (current-&gt;val == 0) {\r\n            ptr0-&gt;next = current;\r\n            ptr0 = ptr0-&gt;next;\r\n            current = current-&gt;next;\r\n        } else if (current-&gt;val == 1) {\r\n            ptr1-&gt;next = current;\r\n            ptr1 = ptr1-&gt;next;\r\n            current = current-&gt;next;\r\n        } else {\r\n            ptr2-&gt;next = current;\r\n            ptr2 = ptr2-&gt;next;\r\n            current = current-&gt;next;\r\n        }\r\n    }\r\n\r\n    \/\/ connect the 2 linked lists.\r\n    ptr0-&gt;next = (temp1-&gt;next)\r\n    ? (temp1-&gt;next) : (temp2-&gt;next);\r\n    ptr1-&gt;next = temp2-&gt;next;\r\n    ptr2-&gt;next = NULL;\r\n\r\n    \/\/ Updating the head\r\n    head = temp0-&gt;next;\r\n\r\n    \/\/ Deletion of dummy nodes\r\n    delete temp0;\r\n    delete temp1;\r\n    delete temp2;\r\n\r\n    return head;\r\n}\r\n\r\n\/\/ Creating and returning a node.\r\nNode* newNode(int val)\r\n{\r\n    Node* newNode = new Node;\r\n    newNode-&gt;val = val;\r\n    newNode-&gt;next = NULL;\r\n}\r\n\r\n\/\/ Function to display the Linked List\r\nvoid displayList(struct Node* node)\r\n{\r\n    while (node != NULL) {\r\n        cout&lt;&lt;node-&gt;val&lt;&lt;&rdquo; &ldquo;;\r\n        node = node-&gt;next;\r\n    }\r\n    cout&lt;&lt;endl;\r\n}\r\n\r\n\/\/ Driver function\r\nint main()\r\n{\r\n    \/\/ Creation of list\r\n    Node* head = newNode(1);\r\n    head-&gt;next = newNode(2);\r\n    head-&gt;next-&gt;next = newNode(0);\r\n    head-&gt;next-&gt;next-&gt;next = newNode(1);\r\n     head-&gt;next-&gt;next-&gt;next-&gt;next = newNode(0);\r\n\r\n    cout&lt;&lt;&quot;Original Linked List:&rdquo;&lt;&lt;endl;\r\n    displayList(head);\r\n\r\n    head = sortingLL(head);\r\n\r\n    cout&lt;&lt;&quot;Sorted Linked List:&rdquo;&lt;&lt;endl;\r\n    displayList(head);\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_4328_3\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"Java\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"Java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\nclass Node\r\n{\r\n\tint data;\r\n\tNode next;\r\n\tNode(int data)\r\n\t{\r\n\t\tthis.data=data;\r\n\t}\r\n}\r\n\r\n\r\nclass SortIt \r\n{\r\n\tpublic static Node sortList(Node head)\r\n\t{\r\n\t\tif(head==null || head.next==null)\r\n\t\t{\r\n\t\t\treturn head;\r\n\t\t}\r\n\t\tNode zeroD = new Node(0);\r\n\t\tNode oneD = new Node(0);\r\n\t\tNode twoD = new Node(0);\r\n\r\n\t\tNode zero = zeroD, one = oneD, two = twoD;\r\n\t\tNode curr = head;\r\n\t\twhile (curr!=null)\r\n\t\t{\r\n\t\t\tif (curr.data == 0)\r\n\t\t\t{\r\n\t\t\t\tzero.next = curr;\r\n\t\t\t\tzero = zero.next;\r\n\t\t\t\tcurr = curr.next;\r\n\t\t\t}\r\n\t\t\telse if (curr.data == 1)\r\n\t\t\t{\r\n\t\t\t\tone.next = curr;\r\n\t\t\t\tone = one.next;\r\n\t\t\t\tcurr = curr.next;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttwo.next = curr;\r\n\t\t\t\ttwo = two.next;\r\n\t\t\t\tcurr = curr.next;\r\n\t\t\t}\r\n\t\t}\r\n\t\tzero.next = (oneD.next!=null)? (oneD.next) : (twoD.next);\r\n\t\tone.next = twoD.next;\r\n\t\ttwo.next = null;\r\n\t\thead = zeroD.next;\r\n\t\treturn head;\r\n\t}\r\n\t\/\/ function to create and return a node\r\n\tpublic static Node newNode(int data)\r\n\t{\r\n\t\t\/\/ allocating space\r\n\t\tNode newNode = new Node(data);\r\n\t\tnewNode.next = null;\r\n\t\treturn newNode;\r\n\t}\r\n\t\/* Function to print linked list *\/\r\n\tpublic static void printList(Node node)\r\n\t{\r\n\t\twhile (node != null)\r\n\t\t{\r\n\t\t\tSystem.out.print(node.data+&quot; &quot;);\r\n\t\t\tnode = node.next;\r\n\t\t}\r\n\t}\r\n\tpublic static void main(String args[]) \r\n    {\r\n\t\tNode head = new Node(1);\r\n\t\thead.next = new Node(2);\r\n\t\thead.next.next = new Node(0);\r\n\t\thead.next.next.next = new Node(1);\r\n\t\tSystem.out.println(&quot;Linked List Before Sorting&quot;);\r\n\t\tprintList(head);\r\n\t\thead = sortList(head);\r\n\t\tSystem.out.println(&quot;Linked List After Sorting&quot;);\r\n\t\tprintList(head);\r\n\t}\r\n}\r\n\r\n\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_4328_4\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"Python\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"Python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\n# Link list node\r\nclass Node:\r\n\tdef __init__(self, data):\r\n\t\tself.data = data\r\n\t\tself.next = None\r\n\r\n# Sort a linked list of 0s, 1s and 2s\r\n# by changing poers.\r\ndef sortList(head):\r\n\tif (head == None or\r\n\t\thead.next == None):\r\n\t\treturn head\r\n\r\n\t# Create three dummy nodes to point to\r\n\t# beginning of three linked lists.\r\n\t# These dummy nodes are created to\r\n\t# avoid many None checks.\r\n\tzeroD = Node(0)\r\n\toneD = Node(0)\r\n\ttwoD = Node(0)\r\n\r\n\t# Initialize current pointers for three\r\n\t# lists and whole list.\r\n\tzero = zeroD\r\n\tone = oneD\r\n\ttwo = twoD\r\n\r\n\t# Traverse list\r\n\tcurr = head\r\n\twhile (curr):\r\n\t\tif (curr.data == 0):\r\n\t\t\tzero.next = curr\r\n\t\t\tzero = zero.next\r\n\t\t\tcurr = curr.next\r\n\t\telif(curr.data == 1):\r\n\t\t\tone.next = curr\r\n\t\t\tone = one.next\r\n\t\t\tcurr = curr.next\r\n\t\telse:\r\n\t\t\ttwo.next = curr\r\n\t\t\ttwo = two.next\r\n\t\t\tcurr = curr.next\r\n\t\t\r\n\t# Attach three lists\r\n\tzero.next = (oneD.next) if (oneD.next ) &#92;\r\n\t\t\t\t\t\t\telse (twoD.next)\r\n\tone.next = twoD.next\r\n\ttwo.next = None\r\n\r\n\t# Updated head\r\n\thead = zeroD.next\r\n\r\n\t# Delete dummy nodes\r\n\treturn head\r\n\r\n# function to create and return a node\r\ndef newNode(data):\r\n\t\r\n\tnewNode = Node(data)\r\n\tnewNode.data = data\r\n\tnewNode.next = None\r\n\treturn newNode\r\n\r\n# Function to print linked list\r\ndef printList(node):\r\n\twhile (node != None):\r\n\t\tprint(node.data, end = &quot; &quot;)\r\n\t\tnode = node.next\r\n\t\r\nif __name__=='__main__':\r\n\t\r\n\t# Creating the list 1.2.4.5\r\n\thead = newNode(1)\r\n\thead.next = newNode(2)\r\n\thead.next.next = newNode(0)\r\n\thead.next.next.next = newNode(1)\r\n\thead.next.next.next.next = newNode(0)\r\n\r\n\tprint(&quot;Linked List Before Sorting&quot;)\r\n\tprintList(head)\r\n\r\n\thead = sortList(head)\r\n\r\n\tprint(&quot;&#92;nLinked List After Sorting&quot;)\r\n\tprintList(head)\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_4328 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_4328 a\"),jQuery(\"#tab-content_4328\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<h3>Output:<\/h3>\n<p>Original Linked List:<br \/>\n1  2  0  1  0<br \/>\nSorted Linked List:<br \/>\n0  0  1  1  2  <\/p>\n<p><strong>Time Complexity:<\/strong> O(n), where n is the number of nodes in the linked list.<\/p>\n<p>In this article, we have explained how to sort a linked list of 0s 1s and 2s. Different approaches have been explained to sort linked list of 0 1 2 with pictorial dry run and code implementation with all time and space complexities. To explore more on the linked list you can follow this link <a href=\"https:\/\/mycode.prepbytes.com\/interview-coding\/practice\/linked-list\">Linked List<\/a>, which is curated by our expert mentors at PrepBytes Footer<\/p>\n<table width=\"641\">\n<tbody>\n<tr>\n<td colspan=\"2\" width=\"641\" style=\"text-align: center\"><strong>Related Articles<\/strong><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/doubly-circular-linked-list-introduction-and-insertion\/\">Doubly circular linked list in data structure<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/advantages-disadvantages-and-uses-of-a-doubly-linked-list\/\">Application of doubly linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/applications-of-linked-list-data-structure\/\">Applications of linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/difference-between-a-singly-linked-list-and-a-doubly-linked-list\/\">Singly linked list vs doubly linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/advantage-and-disadvantage-of-linked-list-over-array\/\">Advantages and disadvantages of linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/menu-driven-program-for-all-operations-on-doubly-linked-list-in-c\/\">Doubly linked list all operations in C<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/binary-search\/binary-search-on-linked-list\/\">Binary search in linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/bubble-sort-for-linked-list-by-swapping-nodes\/\">Bubble sort linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/delete-a-node-in-doubly-linked-list\/\">Deletion in doubly linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/delete-middle-of-linked-list\/\">Delete the middle node of a linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/adding-two-polynomials-using-linked-list\/\">Polynomial addition using linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/find-the-smallest-and-largest-elements-in-a-singly-linked-list\/\">Find max value and min value in linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/insert-a-node-at-a-specific-position-in-a-linked-list\/\">Insert a node at a specific position in a linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/swap-nodes-in-a-linked-list-without-swapping-data\/\">Swap nodes in linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/add-two-numbers-represented-by-linked-lists-set-1\/\">Add two numbers represented by linked lists<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/find-the-first-node-of-the-loop-in-a-linked-list\/\">Find starting point of loop in linked list<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/merge-sort-on-a-singly-linked-list\/\">Merge sort linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/delete-a-node-at-a-given-position\/\">Delete a node from linked list at a given position<\/a><\/td>\n<\/tr>\n<tr>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/linked-list\/remove-duplicates-from-an-unsorted-linked-list\/\">Remove duplicates from unsorted linked list<\/a><\/td>\n<td width=\"321\"><a href=\"https:\/\/prepbytes.com\/blog\/python\/python-program-to-reverse-a-linked-list\/\">Reverse a linked list in Python<\/a><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>FAQs to sort a linked list of 0s 1s and 2s<\/h2>\n<p><ol><strong><\/p>\n<li>Can we reverse a linked list in less than O(N)?<\/li>\n<p><\/strong><br \/>\nIt is not possible to reverse a simple singly linked list in less than O(n).<br \/>\n<strong><\/p>\n<li>What is a linked list?<\/li>\n<p><\/strong><br \/>\nA linked list is a sequence of data structures, which are connected together via links and each node points to the next node.<br \/>\n<strong><\/p>\n<li>Is the linked list allow null values?<\/li>\n<p><\/strong><br \/>\nThe linked list allows any number of null values while LinkedHashSet also allows a maximum of one null element.<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn to sort a linked list of 0s 1s and 2s. Sorting an array implies that the elements present in the array must be present in a particular order, whether in ascending order or in descending order. Let\u2019s try to understand to sort linked list of 0 1 2 Problem [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[125],"tags":[],"class_list":["post-4327","post","type-post","status-publish","format-standard","hentry","category-linked-list"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.8 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Sort a linked list of 0s, 1s, and 2s by changing links<\/title>\n<meta name=\"description\" content=\"Learn the most efficient way to sort a linked list of 0&#039;s, 1&#039;s, and 2&#039;s by changing links. This blog explains the most efficient algorithm for sorting a linked list of 0s, 1s, and 2s by changing links.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Sort a linked list of 0s, 1s, and 2s by changing links\" \/>\n<meta property=\"og:description\" content=\"Learn the most efficient way to sort a linked list of 0&#039;s, 1&#039;s, and 2&#039;s by changing links. This blog explains the most efficient algorithm for sorting a linked list of 0s, 1s, and 2s by changing links.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/\" \/>\n<meta property=\"og:site_name\" content=\"PrepBytes Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/prepbytes0211\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-08-25T08:43:32+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-11-18T07:19:40+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926302503-113.Sort%20a%20linked%20list%20of%200s%2C%201s%2C%20and%202s%20by%20changing%20links_Artboard%202.png\" \/>\n<meta name=\"author\" content=\"PrepBytes\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"PrepBytes\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/\"},\"author\":{\"name\":\"PrepBytes\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/39fcf072e04987f16796546f2ca83c2e\"},\"headline\":\"Sort a linked list of 0s, 1s, and 2s by changing links\",\"datePublished\":\"2021-08-25T08:43:32+00:00\",\"dateModified\":\"2022-11-18T07:19:40+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/\"},\"wordCount\":1081,\"commentCount\":0,\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926302503-113.Sort%20a%20linked%20list%20of%200s%2C%201s%2C%20and%202s%20by%20changing%20links_Artboard%202.png\",\"articleSection\":[\"Linked list articles\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/\",\"url\":\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/\",\"name\":\"Sort a linked list of 0s, 1s, and 2s by changing links\",\"isPartOf\":{\"@id\":\"http:\/\/43.205.93.38\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926302503-113.Sort%20a%20linked%20list%20of%200s%2C%201s%2C%20and%202s%20by%20changing%20links_Artboard%202.png\",\"datePublished\":\"2021-08-25T08:43:32+00:00\",\"dateModified\":\"2022-11-18T07:19:40+00:00\",\"description\":\"Learn the most efficient way to sort a linked list of 0's, 1's, and 2's by changing links. This blog explains the most efficient algorithm for sorting a linked list of 0s, 1s, and 2s by changing links.\",\"breadcrumb\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#primaryimage\",\"url\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926302503-113.Sort%20a%20linked%20list%20of%200s%2C%201s%2C%20and%202s%20by%20changing%20links_Artboard%202.png\",\"contentUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926302503-113.Sort%20a%20linked%20list%20of%200s%2C%201s%2C%20and%202s%20by%20changing%20links_Artboard%202.png\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/43.205.93.38\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Linked list articles\",\"item\":\"https:\/\/prepbytes.com\/blog\/category\/linked-list\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Sort a linked list of 0s, 1s, and 2s by changing links\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/43.205.93.38\/#website\",\"url\":\"http:\/\/43.205.93.38\/\",\"name\":\"PrepBytes Blog\",\"description\":\"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING\",\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/43.205.93.38\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"http:\/\/43.205.93.38\/#organization\",\"name\":\"Prepbytes\",\"url\":\"http:\/\/43.205.93.38\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"contentUrl\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"width\":160,\"height\":160,\"caption\":\"Prepbytes\"},\"image\":{\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/prepbytes0211\/\",\"https:\/\/www.instagram.com\/prepbytes\/\",\"https:\/\/www.linkedin.com\/company\/prepbytes\/\",\"https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA\"]},{\"@type\":\"Person\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/39fcf072e04987f16796546f2ca83c2e\",\"name\":\"PrepBytes\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/850669d326db1e1531f04db0c63145d941c2a26792aaeee226a9e6675b0ac698?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/850669d326db1e1531f04db0c63145d941c2a26792aaeee226a9e6675b0ac698?s=96&d=mm&r=g\",\"caption\":\"PrepBytes\"},\"url\":\"https:\/\/prepbytes.com\/blog\/author\/prepbytes\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Sort a linked list of 0s, 1s, and 2s by changing links","description":"Learn the most efficient way to sort a linked list of 0's, 1's, and 2's by changing links. This blog explains the most efficient algorithm for sorting a linked list of 0s, 1s, and 2s by changing links.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/","og_locale":"en_US","og_type":"article","og_title":"Sort a linked list of 0s, 1s, and 2s by changing links","og_description":"Learn the most efficient way to sort a linked list of 0's, 1's, and 2's by changing links. This blog explains the most efficient algorithm for sorting a linked list of 0s, 1s, and 2s by changing links.","og_url":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/","og_site_name":"PrepBytes Blog","article_publisher":"https:\/\/www.facebook.com\/prepbytes0211\/","article_published_time":"2021-08-25T08:43:32+00:00","article_modified_time":"2022-11-18T07:19:40+00:00","og_image":[{"url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926302503-113.Sort%20a%20linked%20list%20of%200s%2C%201s%2C%20and%202s%20by%20changing%20links_Artboard%202.png","type":"","width":"","height":""}],"author":"PrepBytes","twitter_card":"summary_large_image","twitter_misc":{"Written by":"PrepBytes","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#article","isPartOf":{"@id":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/"},"author":{"name":"PrepBytes","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/39fcf072e04987f16796546f2ca83c2e"},"headline":"Sort a linked list of 0s, 1s, and 2s by changing links","datePublished":"2021-08-25T08:43:32+00:00","dateModified":"2022-11-18T07:19:40+00:00","mainEntityOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/"},"wordCount":1081,"commentCount":0,"publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926302503-113.Sort%20a%20linked%20list%20of%200s%2C%201s%2C%20and%202s%20by%20changing%20links_Artboard%202.png","articleSection":["Linked list articles"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/","url":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/","name":"Sort a linked list of 0s, 1s, and 2s by changing links","isPartOf":{"@id":"http:\/\/43.205.93.38\/#website"},"primaryImageOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#primaryimage"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926302503-113.Sort%20a%20linked%20list%20of%200s%2C%201s%2C%20and%202s%20by%20changing%20links_Artboard%202.png","datePublished":"2021-08-25T08:43:32+00:00","dateModified":"2022-11-18T07:19:40+00:00","description":"Learn the most efficient way to sort a linked list of 0's, 1's, and 2's by changing links. This blog explains the most efficient algorithm for sorting a linked list of 0s, 1s, and 2s by changing links.","breadcrumb":{"@id":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#primaryimage","url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926302503-113.Sort%20a%20linked%20list%20of%200s%2C%201s%2C%20and%202s%20by%20changing%20links_Artboard%202.png","contentUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1644926302503-113.Sort%20a%20linked%20list%20of%200s%2C%201s%2C%20and%202s%20by%20changing%20links_Artboard%202.png"},{"@type":"BreadcrumbList","@id":"https:\/\/prepbytes.com\/blog\/sort-a-linked-list-of-0s-1s-and-2s-by-changing-links\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/43.205.93.38\/"},{"@type":"ListItem","position":2,"name":"Linked list articles","item":"https:\/\/prepbytes.com\/blog\/category\/linked-list\/"},{"@type":"ListItem","position":3,"name":"Sort a linked list of 0s, 1s, and 2s by changing links"}]},{"@type":"WebSite","@id":"http:\/\/43.205.93.38\/#website","url":"http:\/\/43.205.93.38\/","name":"PrepBytes Blog","description":"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING","publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/43.205.93.38\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"http:\/\/43.205.93.38\/#organization","name":"Prepbytes","url":"http:\/\/43.205.93.38\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/","url":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","contentUrl":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","width":160,"height":160,"caption":"Prepbytes"},"image":{"@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/prepbytes0211\/","https:\/\/www.instagram.com\/prepbytes\/","https:\/\/www.linkedin.com\/company\/prepbytes\/","https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA"]},{"@type":"Person","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/39fcf072e04987f16796546f2ca83c2e","name":"PrepBytes","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/850669d326db1e1531f04db0c63145d941c2a26792aaeee226a9e6675b0ac698?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/850669d326db1e1531f04db0c63145d941c2a26792aaeee226a9e6675b0ac698?s=96&d=mm&r=g","caption":"PrepBytes"},"url":"https:\/\/prepbytes.com\/blog\/author\/prepbytes\/"}]}},"_links":{"self":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/4327","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/comments?post=4327"}],"version-history":[{"count":8,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/4327\/revisions"}],"predecessor-version":[{"id":10580,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/4327\/revisions\/10580"}],"wp:attachment":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/media?parent=4327"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/categories?post=4327"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/tags?post=4327"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}