Problem
Problem page: https://leetcode.com/problems/partition-list/
Topics: Linked List, Two Pointers
Difficulty: Medium
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given1->4->3->2->5->2and x = 3,
return1->2->2->4->3->5.
Analysis
After the first node greater than or equal to x, I detach each node less than x in turn and insert it after the initial run of nodes less than x. I start by putting a dummy node new_head before the head. That way, if the first node itself has a value greater than or equal to x (say 4->1 with x=3, which gives 1->4), I don't need a special case for the head pointer.
I skip that initial run since those nodes are already in the right place. l_pos stops at the last node in that run. Then I scan the rest of the list, keeping parent one node behind cur.
If I come across a node less than x, I move it just after l_pos. I then set l_pos to the newly inserted node so the next node less than x goes after it. The nodes with values greater than or equal to x stay where they are, so both parts keep their original order. The time complexity is O(n) because I visit each node only a constant number of times. I only change next pointers, and the dummy node is the only node I create, so the extra space is O(1).
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-partition-list/
