21. Partition List
Given the head
of 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.
Example 1:
Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
Example 2:
Input: head = [2,1], x = 2
Output: [1,2]
Solution: (Using Additional Vector and two traversal)
Solution: (Two pointers)
class Solution
{
public:
ListNode *partition(ListNode *head, int x)
{
ListNode *sm = new ListNode;
ListNode *s = sm;
sm->next = NULL;
sm->val = -5000;
ListNode *gr = new ListNode;
ListNode *g = gr;
gr->next = NULL;
gr->val = 5000;
ListNode *p = head;
while (p)
{
if (p->val < x)
{
s->next = p;
s = s->next;
}
else if (p->val >= x)
{
g->next = p;
g = g->next;
}
p = p->next;
}
g->next = NULL;
if (gr->next)
{
s->next = gr->next;
}
return sm->next;
}
};
Time Complexity: O(n) Space Complexity: O(1)
Last updated
Was this helpful?