题目:
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
.
用两个指针来做,前面一个指针指向的结点,其前面结点对应元素均小于x,后面的指针搜索下一个结点,如果小于x就插入到前一个指针对应结点的后面,否则就跳过。
难点:当头结点改变时的情况。
时间复杂度:O(n)
实现如下:
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode *p = head,*q=head;
while (p!=NULL && p->val >= x)
{
q = p;
p = p->next;
}
if (p == NULL) return head;
if (p != head)
{
q->next = p->next;
p->next = head;
head = p;
}
if (p->next == NULL) return head;
while (q != NULL && q->val < x)
{
p = q;
q = q->next;
}
if (p == NULL || p->next == NULL) return head;
while (q->next!=NULL)
{
if (q->next->val >= x)
{
q = q->next;
continue;
}
ListNode *temp = q->next;
q->next = q->next->next;
temp->next = p->next;
p->next = temp;
p = p->next;
}
return head;
}
};