Partition List
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
.
解题思路:定义head1和head2,遍历链表,将小于x的节点链接到head1后面,将大于等于x的节点连接到head2的后面,最后将head2链接到head1的末尾,返回head1就OK
ListNode *partition(ListNode *head, int x)
{
if (NULL == head)
return NULL;
ListNode head1(0), head2(0);
ListNode* p1 = &head1, *p2 = &head2;
while (head)
{
if (head->val < x)
{
p1->next = head;
p1 = p1->next;
}
else
{
p2->next = head;
p2 = p2->next;
}
head = head->next;
}
p2->next = NULL;
p1->next = head2.next;
return head1.next;
}