题意:将队列按给定值分类,小的在前,大的在后。
思路:简单模拟。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if(!head) return NULL;
ListNode* shead = NULL;
ListNode* bhead = NULL;
ListNode* snext = NULL;
ListNode* bnext = NULL;
ListNode* next =head;
while(next) {
ListNode* now = next;
next = next->next;
if(now->val < x) {
if(!shead) {
shead = now;
snext = now;
snext->next = NULL;
}
else {
snext->next = now;
snext = snext->next;
snext->next = NULL;
}
}
else {
if(!bhead) {
bhead = now;
bnext = now;
bnext->next = NULL;
}
else {
bnext->next = now;
bnext = bnext->next;
bnext->next = NULL;
}
}
}
if(!snext) return bhead;
else {
snext->next = bhead;
return shead;
}
}
};