Python Program For Sorting A Linked List Of 0s, 1s And 2s Last Updated : 18 May, 2022 Comments Improve Suggest changes Like Article Like Report Given a linked list of 0s, 1s and 2s, sort it.Examples: Input: 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> NULL Output: 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2 -> NULL Input: 1 -> 1 -> 2 -> 1 -> 0 -> NULLĀ Output: 0 -> 1 -> 1 -> 1 -> 2 -> NULL Source: Microsoft Interview | Set 1 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Following steps can be used to sort the given linked list. Traverse the list and count the number of 0s, 1s, and 2s. Let the counts be n1, n2, and n3 respectively.Traverse the list again, fill the first n1 nodes with 0, then n2 nodes with 1, and finally n3 nodes with 2. Below image is a dry run of the above approach: Below is the implementation of the above approach: Python # Python program to sort a linked list # of 0, 1 and 2 class LinkedList(object): def __init__(self): # Head of list self.head = None # Linked list Node class Node(object): def __init__(self, d): self.data = d self.next = None def sortList(self): # Initialise count of 0 1 # and 2 as 0 count = [0, 0, 0] ptr = self.head # Count total number of '0', '1' # and '2' # count[0] will store total number # of '0's # count[1] will store total number # of '1's # count[2] will store total number # of '2's while ptr != None: count[ptr.data] += 1 ptr = ptr.next i = 0 ptr = self.head # Let say count[0] = n1, count[1] = n2 # and count[2] = n3 # now start traversing list from head node, # 1) fill the list with 0, till n1 > 0 # 2) fill the list with 1, till n2 > 0 # 3) fill the list with 2, till n3 > 0 while ptr != None: if count[i] == 0: i+=1 else: ptr.data = i count[i] -= 1 ptr = ptr.next # Utility functions # Inserts a new Node at front of # the list. def push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = self.Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # Function to print linked list def printList(self): temp = self.head while temp != None: print str(temp.data), temp = temp.next print '' # Driver code llist = LinkedList() llist.push(0) llist.push(1) llist.push(0) llist.push(2) llist.push(1) llist.push(1) llist.push(2) llist.push(1) llist.push(2) print "Linked List before sorting" llist.printList() llist.sortList() print "Linked List after sorting" llist.printList() # This code is contributed by BHAVYA JAIN Output:Ā Linked List Before Sorting 2 1 2 1 1 2 0 1 0 Linked List After Sorting 0 0 1 1 1 1 2 2 2 Time Complexity: O(n) where n is the number of nodes in the linked list.Ā Auxiliary Space: O(1) Please refer complete article on Sort a linked list of 0s, 1s and 2s for more details! Comment More infoAdvertise with us Next Article Python Program For Sorting A Linked List Of 0s, 1s And 2s kartik Follow Improve Article Tags : Linked List Sorting Python Python Programs DSA Linked Lists Microsoft Amazon MakeMyTrip Linked-List-Sorting Python-DSA +7 More Practice Tags : AmazonMakeMyTripMicrosoftLinked ListpythonSorting +2 More Similar Reads Python Program For Sorting A Linked List Of 0s, 1s And 2s By Changing Links 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, 2Recommended: 3 min read Python Program For Sorting An Array Of 0s, 1s and 2s Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples: Input: {0, 1, 2, 0, 1, 2} Output: {0, 0, 1, 1, 2, 2} Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1} Output: {0, 0, 0, 5 min read Python Program For Merge Sort Of Linked Lists Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible. Let the head be the first node of the linked list to be sorted and headRe 6 min read Python Program For QuickSort On Doubly Linked List Following is a typical recursive implementation of QuickSort for arrays. The implementation uses last element as pivot. Python3 """A typical recursive implementation of Quicksort for array """ """ This function takes last element as pivot, places the pivo 5 min read Python Program For Reversing A Doubly Linked List Given a Doubly Linked List, the task is to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes 4 min read Python Program For Flattening A Linked List Given a linked list where every node represents a linked list and contains two pointers of its type: Pointer to next node in the main list (we call it 'right' pointer in the code below).Pointer to a linked list where this node is headed (we call it the 'down' pointer in the code below). All linked l 4 min read Python Program For Merge Sort For Doubly Linked List Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked l 3 min read Python Program for Segregate 0s and 1s in an array You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Traverse array only once. Example: Input array = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output array = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] Recommended: Please solve it on âPRACTICE â first, before mo 3 min read Python Program For Pairwise Swapping Elements Of A Given Linked List Given a singly linked list, write a function to swap elements pairwise. Input: 1->2->3->4->5->6->NULL Output: 2->1->4->3->6->5->NULL Input: 1->2->3->4->5->NULL Output: 2->1->4->3->5->NULL Input: 1->NULL Output: 1->NULL For examp 2 min read Python Program For Sorting Linked List Which Is Already Sorted On Absolute Values Given a linked list that is sorted based on absolute values. Sort the list based on actual values.Examples: Input: 1 -> -10 Output: -10 -> 1 Input: 1 -> -2 -> -3 -> 4 -> -5 Output: -5 -> -3 -> -2 -> 1 -> 4 Input: -5 -> -10 Output: -10 -> -5 Input: 5 -> 10 Outpu 3 min read Like