题解 | #牛群分隔#
牛群分隔
https://www.nowcoder.com/practice/16d9dc3de2104fcaa52679ea796e638e
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param x int整型
* @return ListNode类
*/
//利用选择排序的思想
ListNode* cow_partition(ListNode* head, int x) {
// write code here
ListNode *p1,*p2=head,*pre2,*tem=nullptr,*tem2=nullptr;
ListNode * vu=new ListNode(0);
vu->next=head;//虚拟头结点
p1=vu;
pre2=vu;
while(p2){
if(p2->val<x){
//P2进入大之后的小了
if(p1->next!=p2){
tem=p1->next;
tem2=p2->next;
//插入p1后
p1->next=p2;
p2->next=tem;
//拔出p2节点
pre2->next=tem2;
p2=pre2;
}
p1=p1->next;
}
pre2=p2;
p2=p2->next;
}
return vu->next;
}
};