Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created December 26, 2018 02:04
Show Gist options
  • Save kanrourou/bee5804f1514227ac1eaee30e3bf424c to your computer and use it in GitHub Desktop.
Save kanrourou/bee5804f1514227ac1eaee30e3bf424c to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* sHead = nullptr, *sCurr = nullptr, *gHead = nullptr, *gCurr = nullptr;
auto curr = head;
while(curr)
{
if(curr->val < x)
{
if(!sHead)
{
sHead = curr;
sCurr = curr;
}
else
{
sCurr->next = curr;
sCurr = sCurr->next;
}
}
else
{
if(!gHead)
{
gHead = curr;
gCurr = curr;
}
else
{
gCurr->next = curr;
gCurr = gCurr->next;
}
}
curr = curr->next;
}
if(sCurr)sCurr->next = gHead;
if(gCurr)gCurr->next = nullptr;
return sHead? sHead : gHead;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment