Given a linked list of 0s, 1s and 2s, sort it.
Examples:
Input : 2->1->2->1->1->2->0->1->0
Output : 0->0->1->1->1->1->2->2->2
The sorted Array is 0, 0, 1, 1, 1, 1, 2, 2, 2.
Input : 2->1->0
Output : 0->1->2
The sorted Array is 0, 1, 2
Method 1: Here is a solution discussed in below post that works by changing data of nodes.
Sort a linked list of 0s, 1s and 2s
The above solution does not work when these values have associated data with them. For example, these three represent three colours and different types of objects associated with the colours and sort the objects (connected with a linked list) based on colours.
Method 2: In this post, a new solution is discussed that works by changing links.
Approach: Iterate through the linked list. Maintain 3 pointers named zero, one and two to point to current ending nodes of linked lists containing 0, 1, and 2 respectively. For every traversed node, we attach it to the end of its corresponding list. Finally, we link all three lists. To avoid many null checks, we use three dummy pointers zeroD, oneD and twoD that work as dummy headers of three lists.
Implementation:
C++
#include <bits/stdc++.h>
struct Node {
int data;
struct Node* next;
};
Node* newNode( int data);
Node* sortList(Node* head)
{
if (!head || !(head->next))
return head;
Node* zeroD = newNode(0);
Node* oneD = newNode(0);
Node* twoD = newNode(0);
Node *zero = zeroD, *one = oneD, *two = twoD;
Node* curr = head;
while (curr) {
if (curr->data == 0) {
zero->next = curr;
zero = zero->next;
}
else if (curr->data == 1) {
one->next = curr;
one = one->next;
}
else {
two->next = curr;
two = two->next;
}
curr = curr->next;
}
zero->next = (oneD->next) ? (oneD->next) : (twoD->next);
one->next = twoD->next;
two->next = NULL;
head = zeroD->next;
delete zeroD;
delete oneD;
delete twoD;
return head;
}
Node* newNode( int data)
{
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
}
void printList( struct Node* node)
{
while (node != NULL) {
printf ( "%d " , node->data);
node = node->next;
}
printf ( "\n" );
}
int main( void )
{
Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(0);
head->next->next->next = newNode(1);
printf ( "Linked List Before Sorting\n" );
printList(head);
head = sortList(head);
printf ( "Linked List After Sorting\n" );
printList(head);
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* newNode( int data);
Node* sortList(Node* head)
{
if (!head || !(head->next))
return head;
Node* zeroD = newNode(0);
Node* oneD = newNode(0);
Node* twoD = newNode(0);
Node *zero = zeroD, *one = oneD, *two = twoD;
Node* curr = head;
while (curr) {
if (curr->data == 0) {
zero->next = curr;
zero = zero->next;
}
else if (curr->data == 1) {
one->next = curr;
one = one->next;
}
else {
two->next = curr;
two = two->next;
}
curr = curr->next;
}
zero->next = (oneD->next) ? (oneD->next) : (twoD->next);
one->next = twoD->next;
two->next = NULL;
head = zeroD->next;
free (zeroD);
free (oneD);
free (twoD);
return head;
}
Node* newNode( int data)
{
Node* newNode = (Node*) malloc ( sizeof (Node));
newNode->data = data;
newNode->next = NULL;
}
void printList( struct Node* node)
{
while (node != NULL) {
printf ( "%d " , node->data);
node = node->next;
}
printf ( "\n" );
}
int main( void )
{
Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(0);
head->next->next->next = newNode(1);
printf ( "Linked List Before Sorting\n" );
printList(head);
head = sortList(head);
printf ( "Linked List After Sorting\n" );
printList(head);
return 0;
}
|
Java
public class Sort012 {
public static Node sortList(Node head)
{
if (head== null || head.next== null )
{
return head;
}
Node zeroD = new Node( 0 );
Node oneD = new Node( 0 );
Node twoD = new Node( 0 );
Node zero = zeroD, one = oneD, two = twoD;
Node curr = head;
while (curr!= null )
{
if (curr.data == 0 )
{
zero.next = curr;
zero = zero.next;
curr = curr.next;
}
else if (curr.data == 1 )
{
one.next = curr;
one = one.next;
curr = curr.next;
}
else
{
two.next = curr;
two = two.next;
curr = curr.next;
}
}
zero.next = (oneD.next!= null )
? (oneD.next) : (twoD.next);
one.next = twoD.next;
two.next = null ;
head = zeroD.next;
return head;
}
public static Node newNode( int data)
{
Node newNode = new Node(data);
newNode.next = null ;
return newNode;
}
public static void printList(Node node)
{
while (node != null )
{
System.out.print(node.data+ " " );
node = node.next;
}
}
public static void main(String args[]) {
Node head = new Node( 1 );
head.next = new Node( 2 );
head.next.next = new Node( 0 );
head.next.next.next = new Node( 1 );
System.out.println("
Linked List Before Sorting");
printList(head);
head = sortList(head);
System.out.println("
\nLinked List After Sorting");
printList(head);
}
}
class Node
{
int data;
Node next;
Node( int data)
{
this .data=data;
}
}
|
Python3
import math
class Node:
def __init__( self , data):
self .data = data
self . next = None
def sortList(head):
if (head = = None or
head. next = = None ):
return head
zeroD = Node( 0 )
oneD = Node( 0 )
twoD = Node( 0 )
zero = zeroD
one = oneD
two = twoD
curr = head
while (curr):
if (curr.data = = 0 ):
zero. next = curr
zero = zero. next
curr = curr. next
elif (curr.data = = 1 ):
one. next = curr
one = one. next
curr = curr. next
else :
two. next = curr
two = two. next
curr = curr. next
zero. next = (oneD. next ) if (oneD. next ) \
else (twoD. next )
one. next = twoD. next
two. next = None
head = zeroD. next
return head
def newNode(data):
newNode = Node(data)
newNode.data = data
newNode. next = None
return newNode
def printList(node):
while (node ! = None ):
print (node.data, end = " " )
node = node. next
if __name__ = = '__main__' :
head = newNode( 1 )
head. next = newNode( 2 )
head. next . next = newNode( 0 )
head. next . next . next = newNode( 1 )
print ( "Linked List Before Sorting" )
printList(head)
head = sortList(head)
print ( "\nLinked List After Sorting" )
printList(head)
|
C#
using System;
public class Sort012
{
public static Node sortList(Node head)
{
if (head == null || head.next == null )
{
return head;
}
Node zeroD = new Node(0);
Node oneD = new Node(0);
Node twoD = new Node(0);
Node zero = zeroD, one = oneD, two = twoD;
Node curr = head;
while (curr != null )
{
if (curr.data == 0)
{
zero.next = curr;
zero = zero.next;
curr = curr.next;
}
else if (curr.data == 1)
{
one.next = curr;
one = one.next;
curr = curr.next;
}
else
{
two.next = curr;
two = two.next;
curr = curr.next;
}
}
zero.next = (oneD.next != null )
? (oneD.next) : (twoD.next);
one.next = twoD.next;
two.next = null ;
head = zeroD.next;
return head;
}
public static Node newNode( int data)
{
Node newNode = new Node(data);
newNode.next = null ;
return newNode;
}
public static void printList(Node node)
{
while (node != null )
{
Console.Write(node.data + " " );
node = node.next;
}
}
public static void Main()
{
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(0);
head.next.next.next = new Node(1);
Console.WriteLine( "Linked List Before Sorting" );
printList(head);
head = sortList(head);
Console.WriteLine( "\nLinked List After Sorting" );
printList(head);
}
}
public class Node
{
public int data;
public Node next;
public Node( int data)
{
this .data = data;
}
}
|
Javascript
<script>
class Node {
constructor(val) {
this .data = val;
this .next = null ;
}
}
function sortList(head) {
if (head == null || head.next == null ) {
return head;
}
var zeroD = new Node(0);
var oneD = new Node(0);
var twoD = new Node(0);
var zero = zeroD, one = oneD, two = twoD;
var curr = head;
while (curr != null ) {
if (curr.data == 0) {
zero.next = curr;
zero = zero.next;
curr = curr.next;
} else if (curr.data == 1) {
one.next = curr;
one = one.next;
curr = curr.next;
} else {
two.next = curr;
two = two.next;
curr = curr.next;
}
}
zero.next = (oneD.next != null ) ?
(oneD.next) : (twoD.next);
one.next = twoD.next;
two.next = null ;
head = zeroD.next;
return head;
}
function newNode(data) {
var newNode = new Node(data);
newNode.next = null ;
return newNode;
}
function printList(node) {
while (node != null ) {
document.write(node.data + " " );
node = node.next;
}
}
var head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(0);
head.next.next.next = new Node(1);
document.write(
"Linked List Before Sorting<br/>"
);
printList(head);
head = sortList(head);
document.write(
"<br/>Linked List After Sorting<br/>"
);
printList(head);
</script>
|
Output
Linked List Before Sorting
1 2 0 1
Linked List After Sorting
0 1 1 2
Complexity Analysis:
- Time Complexity: O(n) where n is a number of nodes in linked list.
Only one traversal of the linked list is needed.
- Auxiliary Space: O(1).
As no extra space is required.
Thanks to Musarrat_123 for suggesting above solution in a comment here.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
10 Jan, 2023
Like Article
Save Article