链表分割_牛客题霸_牛客网 (nowcoder.com) ( 点击前面链接即可查看题目)
/*
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)
{
// write code here
ListNode* tail1, *pHead1, *tail2, *pHead2;
tail1 = pHead1 = (ListNode*)malloc(sizeof(ListNode));
tail2 = pHead2 = (ListNode*)malloc(sizeof(ListNode));
ListNode* cur = pHead;
while (cur)
{
//小于x放入链表1
if (cur->val < x)
{
tail1->next = cur;
tail1 = tail1->next;
}
//大于等于放入链表2
else
{
tail2->next = cur;
tail2 = tail2->next;
}
cur = cur->next;
}
tail1->next = pHead2->next;
tail2->next = NULL;
cur = pHead1->next;
free(pHead1);
free(pHead2);
return cur;
}
};