Skip to content

Instantly share code, notes, and snippets.

@abhi1010
Last active August 29, 2015 14:02
Show Gist options
  • Save abhi1010/3ada1d15b5bda319a54c to your computer and use it in GitHub Desktop.
Save abhi1010/3ada1d15b5bda319a54c to your computer and use it in GitHub Desktop.
Partition LInked List such that all values less than x are on left and the rest on the right side.
Node* sendToOtherList(Node* otherSideList, Node* n)
{
n->next = NULL;
if (otherSideList)
{
otherSideList->next = n;
otherSideList = otherSideList->next;
}
else
{
otherSideList = n;
}
return otherSideList;
}
Node* partitionList (Node* node, int middleValue)
{
Node* current = node;
Node* higher = NULL;
Node* lower = NULL;
Node* firstLow = NULL;
while (current != NULL)
{
Node* tmp = current;
current = current->next;
tmp->next = NULL;
if (tmp->data > middleValue)
{
higher = sendToOtherList(higher, tmp);
}
else
{
lower = sendToOtherList(lower, tmp);
if (firstLow == NULL) firstLow = lower;
}
}
lower->next = node;
return firstLow;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment