Python Program For Sorting A Linked List Of 0s, 1s And 2s By Changing Links
Last Updated :
18 May, 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.
Python3
# Python3 Program to sort a linked list
# 0s, 1s or 2s by changing links
import math
# Link list node
class Node:
def __init__(self, data):
self.data = data
self.next = None
#Node* newNode( data)
# Sort a linked list of 0s, 1s
# and 2s by changing pointers.
def sortList(head):
if (head == None or
head.next == None):
return head
# Create three dummy nodes to point
# to beginning of three linked lists.
# These dummy nodes are created to
# avoid many None checks.
zeroD = Node(0)
oneD = Node(0)
twoD = Node(0)
# Initialize current pointers for
# three lists and whole list.
zero = zeroD
one = oneD
two = twoD
# Traverse list
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
# Attach three lists
zero.next = (oneD.next) if (oneD.next)
else (twoD.next)
one.next = twoD.next
two.next = None
# Updated head
head = zeroD.next
# Delete dummy nodes
return head
# Function to create and return
# a node
def newNode(data):
# Allocating space
newNode = Node(data)
# Inserting the required data
newNode.data = data
newNode.next = None
return newNode
# Function to print linked list
def prList(node):
while (node != None):
print(node.data, end = " ")
node = node.next
# Driver Code
if __name__=='__main__':
# Creating the list 1.2.4.5
head = newNode(1)
head.next = newNode(2)
head.next.next = newNode(0)
head.next.next.next = newNode(1)
print("Linked List Before Sorting")
prList(head)
head = sortList(head)
print("Linked List After Sorting")
prList(head)
# This code is contributed by Srathore
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!
Similar Reads
Python Program For Sorting A Linked List Of 0s, 1s And 2s 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 "PRAC
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 Pairwise Swapping Elements Of A Given Linked List By Changing Links Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function sh
4 min read
Python Program For Alternating Split Of A Given Singly Linked List- Set 1 Write a function AlternatingSplit() that takes one list and divides up its nodes to make two smaller lists 'a' and 'b'. The sublists should be made from alternating elements in the original list. So if the original list is 0->1->0->1->0->1 then one sublist should be 0->0->0 and
3 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 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 Finding Intersection Of Two Sorted Linked Lists Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory â the original lists should not be changed. Example: Input: First linked list: 1->2->3->4->6 Second linked list be 2->4->6->8, Ou
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 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
Python3 Program for Clockwise rotation of Linked List Write a Python3 program for a given singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL, K = 2 Output: 4 -> 5 -> 1 -> 2 -> 3 -> NULLInput: 7 -> 9 -> 11 -> 1
5 min read