Suppose we have a singly linked list and another value k. We have to arrange the nodes so that all nodes whose values are less than k come first, and all nodes whose values are equal to k next, and finally other nodes at last. The constraint is that the relative ordering of the nodes should remain the same.
So, if the input is like L = [4, 3, 6, 6, 6, 10, 8] k = 6, then the output will be [4, 3, 6, 6, 6, 10, 8, ]
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def print_list(head): ptr = head print('[', end = "") while ptr: print(ptr.val, end = ", ") ptr = ptr.next print(']') class Solution: def solve(self, node, k): less_head = less = ListNode(0) equal_head = equal = ListNode(0) greater_head = greater = ListNode(0) cur = node while cur: if cur.val < k: less.next = ListNode(cur.val) less = less.next elif cur.val > k: greater.next = ListNode(cur.val) greater = greater.next else: equal.next = ListNode(cur.val) equal = equal.next cur = cur.next less.next = equal_head.next equal.next = greater_head.next return less_head.next ob = Solution() L = make_list([4, 3, 6, 6, 6, 10, 8]) k = 6 print_list(ob.solve(L, k))
[4, 3, 6, 6, 6, 10, 8], 6
[4, 3, 6, 6, 6, 10, 8, ]