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,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
1:特殊情况;2:把链表分成两个子链表;3:最后考虑如果一个子链表为空的情况
ListNode *partition(ListNode *head,int x)
{
if(head == NULL || head->next == NULL)
{
return head;
}
ListNode* newHead = NULL;
ListNode* index = NULL;
ListNode* bigHead = NULL;
ListNode* bigIndex = NULL;
ListNode* curNode = head;
while(curNode)
{
if(curNode->val >= x)
{
if(bigHead == NULL)
{
bigHead = curNode;
bigIndex = bigHead;
}
else
{
bigIndex->next = curNode;
bigIndex = bigIndex->next;
}
curNode = curNode->next;
}
else
{
if(newHead == NULL)
{
newHead = curNode;
index = newHead;
}
else
{
index->next = curNode;
index = index->next;
}
curNode = curNode->next;
}
}
if(index)
{
index->next = bigHead;
if(bigIndex)
{
bigIndex->next = NULL;
}
}
else
{
newHead = bigHead;
bigIndex->next = NULL;
}
return newHead;
}