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的值记录前一个节点,为当前节点记录前一个节点;
进行值替换位置时,需要注意头节点的变化,主要通过最大值和最大值的前一个节点是否是同一个节点来判断。
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if(head == NULL)
return NULL;
if(head->next == NULL )
{
return head;
}
ListNode * p;
if(head->next->val <x && head->val >= x && head->next->next == NULL)
{
p = head->next;
head->next->next = head;
head->next = NULL;
return p;
}
ListNode * p_pre;//当前节点的前一个节点
ListNode * pre;//当前最大值的前一个节点
ListNode * q;//旧链表的第一个节点
p = head;
pre = p;
p_pre = p;
ListNode * large= NULL;
while(p!=NULL)
{
if(p->val >= x && large == NULL)
{
large = p;
}
else if(p->val < x && large!=NULL)
{
q = p->next;
if(pre!=large)
{
pre->next = p;
p->next = large;
pre =pre->next;
p_pre->next = q;
p = q;
continue;
}
else
{
p->next = large;
head = p;
p_pre->next = q;
pre = p;
p = q;
continue;
}
}
p_pre = p;
p = p->next;
}
return head;
}
};