• 0

Partition a linked list around a value

Problem description :

Write code to partition a linked list around a value val, such that all nodes less than val come before all nodes greater than or equal to val.

Input : A linked list
Output : A linked list

Logic :

  • Create two linked list: one for beforeVal and afterVal.
  • Iterate through the list :
    • Add nodes to beforeVal if its less than val.
    • Add nodes to afterVal if its greater than val.
  • Merge two linked lists.

This post is a follow-up of JavaScript Linked List Example. I recommend reading that first, as the following code uses the method from it.

Solution :