![](https://i-blog.csdnimg.cn/direct/56fbcdd1e015431c95bbce837f8d9212.png)
代码:
cpp
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
//创建两个非空链表:小链表和大链表
ListNode* lesstHead,*lesstTail;
lesstHead = lesstTail = (ListNode*)malloc(sizeof(ListNode));
ListNode* greaterHead,*greaterTail;
greaterHead = greaterTail = (ListNode*)malloc(sizeof(ListNode));
//创建临时变量来遍历原数组
ListNode* prev = pHead;
while(prev)
{
//判断当前节点是否小于x
if(prev->val < x)
{
//插入到小链表中
lesstTail->next = prev;
lesstTail = lesstTail->next;
}
else
{
//插入到大链表中
greaterTail->next = prev;
greaterTail = greaterTail->next;
}
prev = prev->next;
}
//退出循环原链表遍历完成
//连接两个链表
lesstTail->next = greaterHead->next;
ListNode* ret = lesstHead->next;
free(lesstHead);
lesstHead = NULL;
free(greaterHead);
greaterHead = NULL;
return ret;
}
};
提交结果:
![](https://i-blog.csdnimg.cn/direct/e6df0d44195746c79d3d8e1e05a8da12.png)
当我们提交代码之后代码有问题,那么代码到底哪里的逻辑不合适呢?我们画图看一下。
![](https://i-blog.csdnimg.cn/direct/2813e8d7cc3e4fb5bb1d854f481db211.png)
cpp
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
//创建两个非空链表:小链表和大链表
ListNode* lesstHead,*lesstTail;
lesstHead = lesstTail = (ListNode*)malloc(sizeof(ListNode));
ListNode* greaterHead,*greaterTail;
greaterHead = greaterTail = (ListNode*)malloc(sizeof(ListNode));
//创建临时变量来遍历原数组
ListNode* prev = pHead;
while(prev)
{
//判断当前节点是否小于x
if(prev->val < x)
{
//插入到小链表中
lesstTail->next = prev;
lesstTail = lesstTail->next;
}
else
{
//插入到大链表中
greaterTail->next = prev;
greaterTail = greaterTail->next;
}
prev = prev->next;
}
//将大链表的尾节点的next指针置为NULL
greaterTail->next = NULL;
//连接两个链表
lesstTail->next = greaterHead->next;
ListNode* ret = lesstHead->next;
free(lesstHead);
lesstHead = NULL;
free(greaterHead);
greaterHead = NULL;
return ret;
}
};
提交结果:
![](https://i-blog.csdnimg.cn/direct/3822f9b43ed6423d820297026706361b.png)