21. Partition List
Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]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;
}
};Last updated
