给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
你应该保留两部分内链表节点原有的相对顺序。
Yes
样例
给定链表 1->4->3->2->5->2->null,并且 x=3
返回 1->2->2->4->3->5->null
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param x: an integer
* @return: a ListNode
*/
ListNode *partition(ListNode *head, int x) {
// write your code here
if(head==NULL||head->next==NULL) return head;
ListNode *dummy=new ListNode(-1);
dummy->next=head;
ListNode *pre=dummy;
ListNode *cur=head;
ListNode *firstbigpre=dummy;
int mark=1;
while(cur&&cur->val<x){
cur=cur->next;
pre=pre->next;
firstbigpre=firstbigpre->next;
}
while(cur){
if(cur->val<x){
ListNode *tmp=cur;
pre->next=cur->next;
tmp->next=firstbigpre->next;
firstbigpre->next=tmp;
firstbigpre=firstbigpre->next;
cur=pre->next;/////////////////
}
else{
if(mark){firstbigpre=pre;mark=0;}
pre=pre->next;
cur=cur->next;
}
}
return dummy->next;
}
};