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.
o(N)
题意为将小于特定值x的所有节点均放在不小于x的节点的前面,而且,不能改变原来节点的前后位置。
思路:设置两个链表,一个用于存放值小于x的节点,一个用于存放值不小于x的节点。
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* dummy=new ListNode(-1);
dummy->next=head;
ListNode* cur=dummy,* par,*rec;
while(cur->next!=NULL && cur->next->val<x)
cur=cur->next;
par=cur;
rec=cur->next;
while(cur->next!=NULL){
if(cur->next->val<x){
par=(par->next=cur->next);
cur->next=cur->next->next;
par->next=rec;
} else
cur=cur->next;
}
return dummy->next;
}
};