给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
你应该保留两部分内链表节点原有的相对顺序。
给定链表 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
ListNode *p,*p1;
p=head;
p1=head;
ListNode *k=NULL,*k1=NULL,*head1=NULL;
if(head==NULL){
return head;
}
if(head->next==NULL){
return head;
}
while(1){
if(p==NULL){
if(k!=NULL){
k->next=head;
return head1;
}else{
return head;
}
}
if(p->val<x){
if(p==head){
head=p->next;
p->next=NULL;
k1=p;
if(head1==NULL){
head1=k1;
k=k1;
}else{
k->next=k1;
k=k1;
}
p=head;
}else{
p1->next=p->next;
p->next=NULL;
k1=p;
if(head1==NULL){
head1=k1;
k=k1;
}else{
k->next=k1;
k=k1;
}
p=p1->next;
}
continue;
}
p1=p;
p=p->next;
}
}
};