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