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
andafterVal
. - Iterate through the list :
- Add nodes to
beforeVal
if its less thanval
. - Add nodes to
afterVal
if its greater thanval
.
- Add nodes to
- 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.