Problem Description
Given the head of a linked list and a value x, partition the list such that all nodes with values less than x come before nodes with values greater than or equal to x. The original relative order of the nodes in each partition must be preserved.
Key Insights
- Use two separate lists: one for nodes less than x and one for nodes greater than or equal to x.
- Create dummy nodes for each list to simplify edge case handling.
- Traverse the original list once, partitioning nodes into the two lists.
- Connect the two lists at the end to obtain the final partitioned list.
Space and Time Complexity
Time Complexity: O(n) because we traverse the list once.
Space Complexity: O(1) since we only use a constant number of pointers.
Solution
We maintain two dummy head nodes to start the lists for nodes less than x and nodes greater than or equal to x. As we traverse the original list, we append each node to the appropriate list. After the traversal, we link the end of the less-than list to the head of the greater-than or equal list and set the tail of the greater list to None (or null) to avoid forming a cycle. Finally, we return the new head from the less-than list.