Javascript Program For Sorting A Linked List Of 0s, 1s And 2s By Changing Links
Last Updated :
11 Jan, 2022
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: There 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 colors and different types of objects associated with the colors and sort the objects (connected with a linked list) based on colors.
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.
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.
Please refer complete article on Sort a linked list of 0s, 1s and 2s by changing links for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...