Given the head of a singly linked list consisting of only 0, 1 or 2. Sort the given linked list and return the head of the modified list. Do it in-place by changing the links between the nodes without creating new nodes.
Input: head -> 1 -> 0 -> 2 -> 0 -> 1
Output: head -> 0 -> 0 -> 1 -> 1 -> 2
Explanation: The values after sorting are [0, 0, 1, 1, 2].
Input: head -> 1 -> 1 -> 1 -> 0
Output: head -> 0 -> 1 -> 1 -> 1
Explanation: The values after sorting are [0, 1, 1, 1].
Input: head -> 2 -> 2 -> 1 -> 2
#include <bits/stdc++.h>
using namespace std;
// Definition of singly linked list:
struct ListNode {
int val;
ListNode* next;
ListNode() {
val = 0;
next = NULL;
}
ListNode(int data1) {
val = data1;
next = NULL;
}
ListNode(int data1, ListNode* next1) {
val = data1;
next = next1;
}
};
class Solution {
public:
// Function to sort the linked list
ListNode* sortList(ListNode* head) {
// Initialize counts
int c0 = 0, c1 = 0, c2 = 0;
ListNode* temp = head;
/* Count the number of 0s,
1s, and 2s in the list*/
while (temp != NULL) {
if (temp->val == 0)
c0++;
else if (temp->val == 1)
c1++;
else if (temp->val == 2)
c2++;
temp = temp->next;
}
temp = head;
/* Reassign values to
the nodes based on
the counts*/
while (temp != NULL) {
if (c0 > 0) {
temp->val = 0;
c0--;
} else if (c1 > 0) {
temp->val = 1;
c1--;
} else if (c2 > 0) {
temp->val = 2;
c2--;
}
temp = temp->next;
}
return head;
}
};
// Function to print linked list
void printList(ListNode* head) {
while (head != NULL) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
// Function to create new node
ListNode* newNode(int data) {
ListNode* node = new ListNode(data);
return node;
}
int main() {
// Creating a linked list
ListNode* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(0);
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(1);
// Print original list
cout << "Original list: ";
printList(head);
// Sort the list
Solution sol;
head = sol.sortList(head);
// Print sorted list
cout << "Sorted list: ";
printList(head);
return 0;
}
import java.util.*;
// Definition of singly linked list:
class ListNode {
int val;
ListNode next;
ListNode() {
val = 0;
next = null;
}
ListNode(int data1) {
val = data1;
next = null;
}
ListNode(int data1, ListNode next1) {
val = data1;
next = next1;
}
}
class Solution {
// Function to sort the linked list
public ListNode sortList(ListNode head) {
// Initialize counts
int c0 = 0, c1 = 0, c2 = 0;
ListNode temp = head;
/* Count the number of 0s,
1s, and 2s in the list */
while (temp != null) {
if (temp.val == 0)
c0++;
else if (temp.val == 1)
c1++;
else if (temp.val == 2)
c2++;
temp = temp.next;
}
temp = head;
/* Reassign values to
the nodes based on
the counts */
while (temp != null) {
if (c0 > 0) {
temp.val = 0;
c0--;
} else if (c1 > 0) {
temp.val = 1;
c1--;
} else if (c2 > 0) {
temp.val = 2;
c2--;
}
temp = temp.next;
}
return head;
}
}
// Function to print linked list
public class Main {
public static void printList(ListNode head) {
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println();
}
// Function to create new node
public static ListNode newNode(int data) {
ListNode node = new ListNode(data);
return node;
}
public static void main(String[] args) {
// Creating a linked list
ListNode head = newNode(1);
head.next = newNode(2);
head.next.next = newNode(0);
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(1);
// Print original list
System.out.print("Original list: ");
printList(head);
// Sort the list
Solution sol = new Solution();
head = sol.sortList(head);
// Print sorted list
System.out.print("Sorted list: ");
printList(head);
}
}
# Definition of singly linked list:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
# Function to sort the linked list
def sortList(self, head):
# Initialize counts
c0 = 0
c1 = 0
c2 = 0
temp = head
# Count the number of 0s,
# 1s, and 2s
while temp is not None:
if temp.val == 0:
c0 += 1
elif temp.val == 1:
c1 += 1
elif temp.val == 2:
c2 += 1
temp = temp.next
temp = head
# Reassign values to the
# nodes based on the counts
while temp is not None:
if c0 > 0:
temp.val = 0
c0 -= 1
elif c1 > 0:
temp.val = 1
c1 -= 1
elif c2 > 0:
temp.val = 2
c2 -= 1
temp = temp.next
return head
# Function to print linked list
def printList(head):
while head is not None:
print(head.val, end=" ")
head = head.next
print()
# Function to create new node
def newNode(data):
return ListNode(data)
if __name__ == "__main__":
# Creating a linked list
head = newNode(1)
head.next = newNode(2)
head.next.next = newNode(0)
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(1)
# Print original list
print("Original list: ", end="")
printList(head)
# Sort the list
sol = Solution()
head = sol.sortList(head)
# Print sorted list
print("Sorted list: ", end="")
printList(head)
// Definition of singly linked list:
class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}
class Solution {
// Function to sort the linked list
sortList(head) {
// Initialize counts
let c0 = 0, c1 = 0, c2 = 0;
let temp = head;
/* Count the number of 0s,
1s, and 2s in the list */
while (temp !== null) {
if (temp.val === 0)
c0++;
else if (temp.val === 1)
c1++;
else if (temp.val === 2)
c2++;
temp = temp.next;
}
temp = head;
/* Reassign values to
the nodes based on
the counts */
while (temp !== null) {
if (c0 > 0) {
temp.val = 0;
c0--;
} else if (c1 > 0) {
temp.val = 1;
c1--;
} else if (c2 > 0) {
temp.val = 2;
c2--;
}
temp = temp.next;
}
return head;
}
}
// Function to print linked list
function printList(head) {
while (head !== null) {
process.stdout.write(head.val + " ");
head = head.next;
}
console.log();
}
// Function to create new node
function newNode(data) {
return new ListNode(data);
}
(function() {
// Creating a linked list
let head = newNode(1);
head.next = newNode(2);
head.next.next = newNode(0);
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(1);
// Print original list
process.stdout.write("Original list: ");
printList(head);
// Sort the list
let sol = new Solution();
head = sol.sortList(head);
// Print sorted list
process.stdout.write("Sorted list: ");
printList(head);
})();
#include <bits/stdc++.h>
using namespace std;
// Definition of singly linked list:
struct ListNode {
int val;
ListNode* next;
ListNode() {
val = 0;
next = NULL;
}
ListNode(int data1) {
val = data1;
next = NULL;
}
ListNode(int data1, ListNode* next1) {
val = data1;
next = next1;
}
};
class Solution {
public:
// Function to sort the linked list
ListNode* sortList(ListNode* head) {
/* If the list is empty or has only one
node, return as it is already sorted*/
if (head == NULL || head->next == NULL)
return head;
// Dummy nodes to point to heads of
// three lists
ListNode* zeroHead = new ListNode(-1);
ListNode* oneHead = new ListNode(-1);
ListNode* twoHead = new ListNode(-1);
// Pointers to current last nodes of
// three lists
ListNode* zero = zeroHead;
ListNode* one = oneHead;
ListNode* two = twoHead;
ListNode* temp = head;
/* Traverse the original list
and distribute the nodes
into three lists*/
while (temp != NULL) {
if (temp->val == 0) {
zero->next = temp;
zero = temp;
} else if (temp->val == 1) {
one->next = temp;
one = temp;
} else if (temp->val == 2) {
two->next = temp;
two = temp;
}
temp = temp->next;
}
// Connect the three lists together
zero->next = (oneHead->next) ? oneHead->next : twoHead->next;
one->next = twoHead->next;
two->next = NULL;
// New head of the sorted list
ListNode* newHead = zeroHead->next;
// Delete dummy nodes
delete zeroHead;
delete oneHead;
delete twoHead;
return newHead;
}
};
// Helper function to print linked list
void printList(ListNode* head) {
while (head != NULL) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
// Helper function to create a new node
ListNode* newNode(int data) {
ListNode* node = new ListNode(data);
return node;
}
int main() {
// Creating a linked list
ListNode* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(0);
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(1);
// Print original list
cout << "Original list: ";
printList(head);
// Sort the list
Solution sol;
head = sol.sortList(head);
// Print sorted list
cout << "Sorted list: ";
printList(head);
return 0;
}
import java.util.*;
// Definition of singly linked list:
class ListNode {
int val;
ListNode next;
ListNode() {
val = 0;
next = null;
}
ListNode(int data1) {
val = data1;
next = null;
}
ListNode(int data1, ListNode next1) {
val = data1;
next = next1;
}
}
class Solution {
// Function to sort the linked list
public ListNode sortList(ListNode head) {
/* If the list is empty or has only one
node, return as it is already sorted */
if (head == null || head.next == null)
return head;
// Dummy nodes to point to heads of
// three lists
ListNode zeroHead = new ListNode(-1);
ListNode oneHead = new ListNode(-1);
ListNode twoHead = new ListNode(-1);
// Pointers to current last nodes of
// three lists
ListNode zero = zeroHead;
ListNode one = oneHead;
ListNode two = twoHead;
ListNode temp = head;
/* Traverse the original list
and distribute the nodes
into three lists */
while (temp != null) {
if (temp.val == 0) {
zero.next = temp;
zero = temp;
} else if (temp.val == 1) {
one.next = temp;
one = temp;
} else if (temp.val == 2) {
two.next = temp;
two = temp;
}
temp = temp.next;
}
// Connect the three lists together
zero.next = (oneHead.next != null) ? oneHead.next : twoHead.next;
one.next = twoHead.next;
two.next = null;
// New head of the sorted list
ListNode newHead = zeroHead.next;
// Delete dummy nodes
return newHead;
}
}
// Helper function to print linked list
public class Main {
public static void printList(ListNode head) {
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println();
}
// Helper function to create a new node
public static ListNode newNode(int data) {
return new ListNode(data);
}
public static void main(String[] args) {
// Creating a linked list
ListNode head = newNode(1);
head.next = newNode(2);
head.next.next = newNode(0);
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(1);
// Print original list
System.out.print("Original list: ");
printList(head);
// Sort the list
Solution sol = new Solution();
head = sol.sortList(head);
// Print sorted list
System.out.print("Sorted list: ");
printList(head);
}
}
# Definition of singly linked list:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
# Function to sort the linked list
def sortList(self, head):
'''If the list is empty or has only one
node, return as it is already sorted'''
if head is None or head.next is None:
return head
# Dummy nodes to point to heads of
# three lists
zeroHead = ListNode(-1)
oneHead = ListNode(-1)
twoHead = ListNode(-1)
# Pointers to current last nodes of
# three lists
zero = zeroHead
one = oneHead
two = twoHead
temp = head
'''Traverse the original list
and distribute the nodes
into three lists'''
while temp is not None:
if temp.val == 0:
zero.next = temp
zero = temp
elif temp.val == 1:
one.next = temp
one = temp
elif temp.val == 2:
two.next = temp
two = temp
temp = temp.next
# Connect the three lists together
zero.next = oneHead.next if oneHead.next else twoHead.next
one.next = twoHead.next
two.next = None
# New head of the sorted list
newHead = zeroHead.next
# Return the new head
return newHead
# Helper function to print linked list
def printList(head):
while head is not None:
print(head.val, end=" ")
head = head.next
print()
# Helper function to create a new node
def newNode(data):
return ListNode(data)
if __name__ == "__main__":
# Creating a linked list
head = newNode(1)
head.next = newNode(2)
head.next.next = newNode(0)
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(1)
# Print original list
print("Original list: ", end="")
printList(head)
# Sort the list
sol = Solution()
head = sol.sortList(head)
# Print sorted list
print("Sorted list: ", end="")
printList(head)
// Definition of singly linked list:
class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}
class Solution {
// Function to sort the linked list
sortList(head) {
/* If the list is empty or has only one
node, return as it is already sorted */
if (head === null || head.next === null)
return head;
// Dummy nodes to point to heads of
// three lists
let zeroHead = new ListNode(-1);
let oneHead = new ListNode(-1);
let twoHead = new ListNode(-1);
// Pointers to current last nodes of
// three lists
let zero = zeroHead;
let one = oneHead;
let two = twoHead;
let temp = head;
/* Traverse the original list
and distribute the nodes
into three lists */
while (temp !== null) {
if (temp.val === 0) {
zero.next = temp;
zero = temp;
} else if (temp.val === 1) {
one.next = temp;
one = temp;
} else if (temp.val === 2) {
two.next = temp;
two = temp;
}
temp = temp.next;
}
// Connect the three lists together
zero.next = oneHead.next ? oneHead.next : twoHead.next;
one.next = twoHead.next;
two.next = null;
// New head of the sorted list
let newHead = zeroHead.next;
// Return the new head
return newHead;
}
}
// Helper function to print linked list
function printList(head) {
while (head !== null) {
process.stdout.write(head.val + " ");
head = head.next;
}
console.log();
}
// Helper function to create a new node
function newNode(data) {
return new ListNode(data);
}
(function() {
// Creating a linked list
let head = newNode(1);
head.next = newNode(2);
head.next.next = newNode(0);
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(1);
// Print original list
process.stdout.write("Original list: ");
printList(head);
// Sort the list
let sol = new Solution();
head = sol.sortList(head);
// Print sorted list
process.stdout.write("Sorted list: ");
printList(head);
})();
Q: Why do we need three separate dummy lists instead of modifying the original list?
A: Modifying links directly while traversing can lead to broken links or require multiple scans. Using three separate lists ensures stable sorting without losing track of nodes.
Q: What happens if the input list already has sorted 0s, 1s, and 2s?
A: The algorithm processes the list normally, but no rearrangement is needed since pointers remain unchanged.
Q: How can this be extended to handle a linked list with arbitrary numbers instead of just 0, 1, and 2?
A: Use bucket sort logic but with hash maps to store frequency counts. Instead of three pointers, use multiple dummy lists for each unique value.
Q: Can this be modified to sort linked lists containing values from 0 to k?
A: Yes, generalize it by: Creating k+1 linked lists. Distributing nodes into respective buckets. Merging all buckets into a single list.