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
.
[Solution]
//
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// Definition for Solution
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head != NULL){
ListNode *preBig = head;
ListNode *big = head;
ListNode *preSmall = head;
ListNode *small = head;
while(true){
while(big != NULL && big->val < x){
preBig = big;
big = big->next;
}
// all of the elements are smaller than x
if(big == NULL){
break;
}
// find the next element that smaller than x
small = big;
while(small != NULL && small->val >= x){
preSmall = small;
small = small->next;
}
// the remained are all bigger than or equals to x
if(small == NULL){
break;
}
// the first element is bigger than or equals to x
if(preBig == big){
preSmall->next = small->next;
small->next = big;
head = small;
preBig = small;
}
else{
preSmall->next = small->next;
small->next = big;
preBig->next = small;
preBig = small;
}
}
}
return head;
}
};
说明:版权所有,转载请注明出处。 Coder007的博客