解题思路:
(1)两个链表,一个保存较小值,一个保存较大值
(2)最后较小值链表的尾指针指向较大值链表的头指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode *p=NULL,*q=NULL;
ListNode *proot=NULL,*qroot=NULL;
while(head) {
if(head->val<x) {
if(p!=NULL) {
p->next = head;
p = p->next;
} else {
proot = head;
p = head;
}
} else {
if(q!=NULL) {
q->next = head;
q = q->next;
} else {
qroot = head;
q = head;
}
}
head = head->next;
}
if(proot!=NULL) {
p->next = qroot;
if(qroot!=NULL) {
q->next = NULL;
}
return proot;
} else return qroot;
}
};