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
.
解题思路:这道题其实就是链表的操作,难度在于指针的移动以及边界的检查。说一下我解题的思路大概是这样:
需求:遍历每一个元素,找出小于value的节点,然后将该节点移动到前面某个地方,接下来继续往后遍历。
问题就出来了,当找出小于value节点之后,移动的目的位置如果确定。依据题意,第一次移动的位置就是第一个大于等于value节点的前一个位置,使用一个指针记住这个位置,后面找到的节点依次往后,这样就可以保证相对位置不变。需要注意的一个列外就是,第一个插入的位置是链表头,这时候需要单独处理。代码如下:
ListNode* partition(ListNode* head, int x) {
if(head==NULL||head->next==NULL)
return head;
ListNode* pre=head;
ListNode* first_gre=head;
while(first_gre != NULL && first_gre->val < x){
pre = first_gre;
first_gre = first_gre->next;
}
if(first_gre == NULL || first_gre->next == NULL)
return head;
bool flag=false;
//标识第一次插入为头部
if(first_gre==head)
flag=true;
ListNode* second_pre=first_gre;
while(first_gre->next!=NULL){
first_gre=first_gre->next;
if(first_gre->val < x){
second_pre->next=first_gre->next;
if(flag){
first_gre->next=head;
head=first_gre;
flag=false;
pre=head;
}else{
first_gre->next=pre->next;
pre->next=first_gre;
pre=pre->next;
}
first_gre=second_pre;
if(first_gre==NULL)
break;
// return head;
}else{
second_pre=first_gre;
}
}
return head;
}