编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
ListNode* pNode = pHead;
ListNode* psmallHead = NULL;
ListNode* plargeHead = NULL;
ListNode* psmallTail = NULL;
ListNode* plagerTail = NULL;
while (pNode)
{
if (pNode->val < x)
{
if (!psmallHead)
{
psmallHead = pNode;
psmallTail = psmallHead;
}
else
{
psmallTail->next = pNode;
psmallTail = pNode;
}
}
else
{
if (!plargeHead)
{
plargeHead = pNode;
plagerTail = plargeHead;
}
else
{
plagerTail->next = pNode;
plagerTail = pNode;
}
}
pNode = pNode->next;
}
if (psmallHead == NULL && plargeHead != NULL)
{
plagerTail->next = NULL;
return plargeHead;
}
else if (psmallHead != NULL && plargeHead == NULL)
{
psmallTail->next = NULL;
return psmallHead;
}
else
{
plagerTail->next = NULL;
psmallTail->next = plargeHead;
return psmallHead;
}
}
};