题解 | #链表分割#
链表分割
https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
#include <cstddef>
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
struct ListNode* gGuard,*gTail,*lGuard,*lTail;
struct ListNode*cur = pHead;
gGuard = gTail = (struct ListNode*)malloc(sizeof(struct ListNode));
lGuard = lTail = (struct ListNode*)malloc(sizeof(struct ListNode));
gTail->next = lTail->next = NULL;
while (cur)
{
if (cur->val < x)
{
lTail->next = cur ;
lTail = lTail->next;
}
else
{
gTail->next = cur ;
gTail = gTail->next;
}
cur = cur->next;
}
lTail->next = gGuard->next;
gTail->next = NULL;
pHead = lGuard->next;
free(lGuard);
free(gGuard);
return pHead;
}
};

