Tuesday, August 15th
Linked List Partitioning
Given a linked list and a value x, partition the list so that values less than x occur before values greater than or equal to x, while maintaining the original ordering
A fairly straight-forward linked list problem
First, check if the list is empty
Maintain 2 index pointers, 1 for the less than list and another for the greater than list. Also maintain 2 constant pointers that point to the head of the lesser than list and the greater than list
Traverse the linked list
for each traversed node, check if it's less than or greater that or equal to the target value
If the value is greater than or equal to x, check if the greater than or equal to head node has been set. If so, set the greater-than-or-equal to head node, and also set the g-index node. Otherwise, set the g-index node and traverse the node
Perform the equivalent operations for the less-than-x nodes
Perform a final few operations: set the last node to empty, if the first partition is empty return the second partition, and finally, set the first partition end to the second partition
return the head of the first partition
Straight-forward linked-list problem. Engineering.
Full code below
Comments
Post a Comment