LeetCode练习题,比基准值小的放其前面,否则放后面,且原链表的结点位置关系不变,如 8 2 5 1 6 3 4 9 10,给定基准值7
则结果为 2 5 1 6 3 4 8 9 10
//创建两个链表,一个放比基准值小的,一个放大的,之后再将两链表链接起来即可
//给定基准重新排列链表数据
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
ListNode* partition(struct ListNode* pHead, int x) {
// write code here
if(pHead==NULL){
return pHead;
}
struct ListNode* lt=(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* lh=lt;
struct ListNode* gt=(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* gh=gt;
struct ListNode* cur=pHead;
while(cur){
if(cur->val>=x){
gt->next=cur;
gt=gt->next;
}else{
lt->next=cur;
lt=lt->next;
}
cur=cur->next;
}
//防止出现环
gt->next=NULL;
lt->next=gh->next;
cur=lh->next;
return cur;
}
};